一、屬性
1、第一種使用方法:鍵值對
2、第二種方法:三個點的展開物件形式
var props = { one :”123”, tow :321 } <ClassNameB {…props} />
3、setProps形式:透過元件更新屬性,不能在元件內部修改屬性的,因為會違反組件設計原則(盡量避免)
var instance =React.render(<ClassNameC ><ClaasNameC/>,document.body); instance.setProps({name:”Tom" });
二、狀態:事物所處的狀況,由事物自行處理不斷變化/事物的私有屬性
getInitialState:初始化每個實例特有的狀態
setState:更新組件狀態
setState會觸發diff演算法:判斷state和頁面結果的區別,是否需要更新
三、狀態和屬性對比
狀態和屬性都會觸發render更新,都是純JS物件
狀態:是和自己相關的,既不受父元件也不受子元件影響
屬性:本身是無法自己去修改的,只能從父元件取得屬性,父元件也能修改它的屬性
根本的區別:組件在運作時需要去修改維護的就是狀態
四、簡單的demo熟悉一下:
<!DOCTYPE html> <html> <head> <meta http-equiv='Content-type' content='text/html; charset=utf-8'> <title>daomul's example</title> <link rel="stylesheet" href="../shared/css/base.css" /> </head> <body> <h1>Text demo</h1> <div id="container"> </div> <script src="../shared/thirdparty/es5-shim.min.js"></script> <script src="../shared/thirdparty/es5-sham.min.js"></script> <script src="../shared/thirdparty/console-polyfill.js"></script> <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(event){ this.setState({inputText:event.target.value}); }, handleClick:function(){ console.log("props name is " + this.props.selectName + " \n and inputText is " + this.state.inputText); }, render:function(){ return <div> <textarea onChange = {this.handleChange} placeholder = "please input something!"></textarea> <button onClick = {this.handleClick}>sumbit</button> </div>; }, }); //评论组件 var Comment = React.createClass({ getInitialState:function(){ return { names:["Tom","Axiba","daomul"], selectName:'', }; }, handleSelect:function(){ this.setState( {selectName : event.target.value} ); }, render:function(){ var options = []; //往options中添加子option for (var option in this.state.names) { options.push(<option value={this.state.names[option]}> {this.state.names[option]} </option>) }; return <div> <Content selectName = {this.state.selectName}> </Content> <select onChange = {this.handleSelect}> {options} </select> </div>; }, }); //start render React.render(<Comment></Comment>,document.body); </script> </body> </html>