1.react腳手架:
(1)Npm install react --save
(2)Npm install react-dom --save
(3)Npm install react-router-dom --save
(4)Npm install create-react-app -g
(5)Create-react-app 名字
(6)Npm run eject
(7)Npm start
2.組件:
(1)作用:
①渲染HTML元素
②封裝:可重復使用代碼
(2)三種:
①函數(shù)式:無狀態(tài)組件:
function HelloComponent(props, /* context */) { return <div>Hello {props.name}</div> } ReactDOM.render(<HelloComponent name="Sebastian" />, mountNode)
1.組件不會被實例倦挂,整體渲染性能得到提升
2.組件不能訪問this對象
3.組件無法訪問生命周期的方法
4.Prop不能用this.props調用
②Es5原生:react.createClass
1)React.createClass({ propTypes: {//定義傳入props中的屬性各種類型 initialValue: React.PropTypes.string }, defaultProps: { //組件默認的props對象 initialValue: '' }, // 設置 initial state getInitialState: function() {//組件相關的狀態(tài)對象 return { text: this.props.initialValue || 'placeholder' }; }, handleChange: function(event) { this.setState({ //this represents react component instance text: event.target.value }); }, render: function() { return ( <div> Type something: <input onChange={this.handleChange} value={this.state.text} /> </div> ); } });
③Es6:react.Component
1)class InputControlES6 extends React.Component { constructor(props) { super(props); // 設置 initial state this.state = { text: props.initialValue || 'placeholder' }; // ES6 類中函數(shù)必須手動綁定 this.handleChange = this.handleChange.bind(this); } handleChange(event) { this.setState({ text: event.target.value }); } render() { return ( <div> Type something: <input onChange={this.handleChange} value={this.state.text} /> </div> ); } }
Es6與es5的區(qū)別:
This
Es6不會自動綁定this但Es5會
3.Es6中React.Component綁定this的方法:
1.在constructor里添加:this.函數(shù)名=this.函數(shù)名.bind(this)
2.<div onClick={this.函數(shù)名.bind(this)}></div>
3.<div onClick={()=>{this.函數(shù)名()}}></div>
4.函數(shù)名=()=>{}
4.react 遍歷為什么要key:
(1)提高性能
(2)通過虛擬dom與真實dom比較做判斷
(3)能快速捕獲改變的數(shù)據(jù)