/* *屬性 * 1.如何傳遞屬性 * 2.屬性和狀態區別和聯繫 * * 3.子組件都有一個props屬性對象 * * 4.單線數據流(只能從父組件流向子組件,就是在父組件定義一個屬性,子組件能夠經過this.props.屬性名 接收) * 5.子組件能夠讀取父組件傳遞的屬性,可是不能直接改 * */ import React,{Component} from 'react' import ReactDOM from 'react-dom' //子組件 class LikeButton extends Component{ constructor(){ super(); } render(){ // JS引擎 V8 最多隻會佔用1.7G //onClick等於一個函數定義,而非一個函數執行結果 //若是changeText加上(),則會直接執行,再次執行就沒有結果,還會進入死循環 // 加了(),改變狀態,父組件從新渲染,子組件又會渲染,自主渲染又會修改狀態,父組件又會從新渲染,這樣一直死循環,直到內存消耗光了 return( <button onClick={this.props.changeText}> {this.props.text}{this.props.age} </button> ) } } /*父組件定義一個屬性text*/ class Index extends Component{ constructor(){ super(); //初始化狀態對象 this.state={ text:"點贊", age:10 } } changeText= ()=>{ this.setState({ text:this.state.text=='點贊'?'取消':'點贊' }) } //父組件經過屬性傳遞函數和變量值給子組件 render(){ return( <div> <LikeButton changeText={this.changeText} text={this.state.text} age={this.state.age}></LikeButton> </div> ) } } ReactDOM.render(<Index></Index>,document.querySelector('#root'));