1. 介绍:
对组件的组织和管理方式
目的:
实现:
2. 组件嵌套
组件嵌套本质是父子关系:
实例:
<!DOCTYPE html> <html> <head lang="en"> <Meta charset="UTF-8"> <title></title> <script src="build/react.js"></script> <script src="build/JSXTransformer.js"></script> </head> <body> <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 SingupForm = React.createClass({ getInitialState: function () { return { name:'',password:'',gender:'',} },handerChange: 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.handerChange.bind(this,'name')} /> <input type="password" placeholder="输入密码" onChange={ this.handerChange.bind(this,'password')} /> <GenderSelect handleSelect={this.handleSelect}></GenderSelect> </form> } }) React.render(<SingupForm></SingupForm>,document.body); </script> </body> </html>
3. Mixin
Mixin含义:一组方法,
目的: 横向抽离出组件的相似代码
实例: 数据的双向绑定
<!DOCTYPE html> <html> <head lang="en"> <Meta charset="UTF-8"> <title></title> <script src="build/react.js"></script> <script src="build/JSXTransformer.js"></script> </head> <body> <script type="text/jsx"> var BindingMixin = { handleChange: function (key) { var that = this return function (event) { var newState = {} newState[key] = event.target.value that.setState(newState) } } }; var BindingExmple = React.createClass({ mixins:[BindingMixin],getInitialState : function () { return { text:'',content:'' } },render: function () { return <div> <input type="text" placeholder="输入内容" onChange={this.handleChange('text')} /> <textarea onChange={this.handleChange('content')}></textarea> <p>{this.state.text}</p> <p>{this.state.content}</p> </div> } }); React.render(<BindingExmple></BindingExmple>,document.body); </script> </body> </html>