React属性和状态详解
一、属性的含义和用法 props = properties 3种用法: (1)<HelloWorld key=?/> (key="Tim",key={123},key={"Tim"},key={[1,2,3]},key={variable}) (2)var props = { one:"123", two:321} <HelloWorld{...props}/> (3)调用.setProps({name:"Tim"}); 几乎不使用这个方法
<!DOCTYPE html> <html lang="zn-cn"> <head> <meta charset="UTF-8"> <title>React</title> </head> <body> <script src="./build/react.js"></script> <script src="./build/JSXTransformer.js"></script> <script type="text/jsx"> var style={ color:"red",border:"1px solid #000" }; var HelloWorld = React.createClass({ render:function () { console.log("render,4"); return <p>Hello,{this.props.name1 + ' ' + this.props.name2}</p>; } }); var HelloUniverse = React.createClass({ getInitialState:function () { return { name1:"Tim",name2:"John" }; },handleChange:function (event) { this.setState({name:event.target.value}) },render:function () { return ( <div> <HelloWorld {...this.state}></HelloWorld> <br/> <input type="text" onChange={this.handleChange}/> </div> ) } }); React.render(<div style={style}><HelloUniverse></HelloUniverse></div>,document.body); </script> </body> </html> var instance = React.render(<HelloWorld></HelloWorld>,document.body); instance.setProps({name:'Tim'});
二、状态的含义和用法 state:是可以变化的,由事物自行处理。 getInitialState:初始化每个实例特有的状态 setState:更新组件状态 setState——diff算法——(变化)更新DOM
this.props.name}</p>; } }); var HelloUniverse = React.createClass({ getInitialState:function () { return { name:"Tim" }; },document.body); </script> </body> </html>
三、属性和状态对比 (1)相似点: 都是纯js对象 都会触发render更新 都有确定性 (2)对比:
props不能修改自己的属性。 (3)区分: 组件在运行时需要修改的数据就是状态。
四、属性和状态实例(编写一个简单的文章评论框) 代码如下:
<!DOCTYPE html> <html lang="zn-cn"> <head> <meta charset="UTF-8"> <title>React</title> </head> <body> <script src="./build/react.js"></script> <script src="./build/JSXTransformer.js"></script> <script type="text/jsx"> var Content = React.createClass({ getInitialState:function () { return { inputText:" " } },handleChange:function () { this.setState({inputText:event.target.value}) },handleSubmit:function () { console.log("reply to :" + this.props.selectName + "n" + this.state.inputText); },render:function () { return( <div> <textarea onChange={this.handleChange} placeholder="please enter something..."></textarea> <button onClick={this.handleSubmit}>submit</button> </div> ) } }); var Comment = React.createClass({ getInitialState:function () { return{ names:["Tim","Johm","Hank"],selectName: ' ' }; },handleSelect:function () { this.setState({selectName:event.target.value}) },render:function () { var options = []; for(var option in this.state.names){ options.push(<option value={this.state.names[option]}>{this.state.names[option]}</option>) } return( <div> <select onChange={this.handleSelect}> {options} </select> <Content selectName={this.state.selectName}></Content> </div> ) } }); React.render( <Comment/>,document.body ); </script> </body> </html> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |