react元件通訊
阿新 • • 發佈:2020-09-22
元件傳值
state 和 props 主要的區別在於 props 是不可變的,而 state 可以根據與使用者互動來改變。
這就是為什麼有些容器元件需要定義 state 來更新和修改資料。 而子元件只能通過 props 來傳遞資料。
父傳子
屬性傳值
- 子元件定義接受資料屬性名稱
- 父元件向該屬性賦值
//父元件 class Father extends React.Component { constructor() { super(); this.state = { 屬性名稱:屬性值 } } render(){ return({ <子元件 子元件屬性名稱={this.state.屬性名稱}/> }); } } //子元件接受 class Son extends React.Component{ constructor(props){ super(); this.state = props; } render(){ return( <子元素標籤>{this.state.子元件屬性名稱}</子元素標籤> ); } }
子傳父
回撥函式方式
//父元件 class Father extends React.Component { constructor() { super(); this.state = { 屬性名稱:屬性值 } } // 父元件接受資料定於函式 getData = (需要傳遞給父元件的值)=>{ //拿到子元件傳遞給父元件的值 } render(){ return({ <子元件 子元件屬性名稱={this.state.屬性名稱} 父元件接受資料函式名稱={this.getData}/> }); } }
//子元件接受 class Son extends React.Component{ constructor(props){ super(); this.state = props; } handleClick(需要傳遞給父元件的值){ this.props.父元件接受資料函式名稱(需要傳遞給父元件的值) } render(){ return( <子元素標籤 onClick={()=>{ this.handleClick(需要傳遞給父元件的值); }}>{this.state.子元件屬性名稱}</子元素標籤> ); } }
兄弟元件
通過子傳父,然後再父傳子 實現兄弟元件之間的通訊