组件协同的本质是对组件的一种组织、管理方式。
1.组件嵌套
2.Mixin(混入,把一段代码混到组件中)
一、组件嵌套
本质是父子关系。
父组件 —(属性)—子组件
子组件—(事件处理函数(委托))—父组件
优点:
逻辑清晰:父子关系
代码模块化:同步开发
封装细节
缺点:
编写难度高:处理父子关系
无法掌握细节
实例代码如下:
<!DOCTYPE html> <html lang="zh-cn"> <head> <Meta charset="UTF-8"> <title>父子关系</title> </head> <body> <script src="./build/react.js"></script> <script src="./build/JSXTransformer.js"></script> <script type="text/jsx"> var GenderSelect = React.createClass({ render: function() { return <select onChange={this.props.handleSelect}> <option value="0">男</option> <option value="1">女</option> </select> } }) var SignupForm = React.createClass({ getInitialState: function() { return { name: '',password: '',gender: '',} },handleChange: function(name,event) { var newState = {} newState[name] = event.target.value this.setState(newState) },handleSelect: function(event) { this.setState({gender: event.target.value}) },render: function() { console.log(this.state) return <form> <input type="text" placeholder="请输入用户名" onChange={this.handleChange.bind(this,'name')} /> <input type="password" placeholder="请输入密码" onChange={this.handleChange.bind(this,'password')} /> <GenderSelect handleSelect={this.handleSelect}></GenderSelect> </form> } }) React.render(<SignupForm></SignupForm>,document.body); </script> </body> </html>
二、Mixin编写和使用
Mixin=一组方法
Mixin的目的是横向抽离出组件的相似代码
相似概念:面向切面编程、插件
优点:
代码复用
即插即用
适应性强
缺点:
编写难度高
降低代码可读性
代码如下:
<!DOCTYPE html> <html lang="zh-cn"> <head> <Meta charset="UTF-8"> <title>Mixin</title> </head> <body> <script src="./build/react.js"></script> <script src="./build/JSXTransformer.js"></script> <script type="text/jsx"> /*var BindingExample = React.createClass({ getInitialState:function () { return { text:'' } }, handleChange:function (event) { this.setState({text:event.target.value}); }, render:function () { return <div> <input type="text" placeholder="请输入内容" onChange={this.handleChange}/> <p>{this.state.text}</p> </div> } });*/ var BindingMixin = { handleChange:function (key) { var that = this; return function () { var newState = {}; newState[key] = event.target.value; that.setState(newState); } },}; var BindingExample = React.createClass({ mixins:[BindingMixin],getInitialState:function () { return { text:'',comment:'' } },render:function () { return <div> <input type="text" placeholder="请输入内容" onChange={this.handleChange('text')}/> <textarea onChange={this.handleChange('comment')}></textarea> <p>{this.state.text}</p> <p>{this.state.comment}</p> </div> } }); React.render( <BindingExample></BindingExample>,document.body ); </script> </body> </html>