国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

react 兄弟組件如何調用對方的方法示例

2024-05-06 15:28:32
字體:
來源:轉載
供稿:網友

最近有一個場景是Child2組件點擊讓Child1組件里面的state的值發生改變,Child1是一個公用組件,把里面的state值改為props傳遞,修改內容太多,容易出錯,就想找其他的方法來解決兄弟組件調用方法問題,下面看代碼:

Child1 是第一個子組件

class Child1 extends React.Component { constructor(props) {  super(props);  this.state = {   text:'Child1'  }; } onChange=()=>{  this.setState({   text:'Child1 onChange'  }) } componentDidMount(){  this.props.onRef&&this.props.onRef(this) } render() {  return (   <div>{this.state.text}</div>  ); }}

是第二個子組件,和Child1是兄弟組件;

class Child2 extends React.Component { constructor(props) {  super(props);  this.state = {  }; } render() {  return (   <div onClick={this.props.onClick}>Child2</div>  ); }}

home 父組件

class Home extends React.Component { constructor(props) {  super(props);  this.state = {  }; } onRef=(ref)=>{  this.child1=ref; } render() {  return (   <div className="home">    <Child1 onRef={this.onRef}/>    <Child2 onClick={     ()=>{      this.child1.onChange&&this.child1.onChange()     }    } />    </div>  ); }}

分析

第一步:在Child1組件的componentDidMount生命周期里面加上this.props.onRef(this),把Child1都傳遞給父組件, 第二步父組件里面 <Child1 onRef={this.onRef}/> this.onRef方法為onRef=(ref)=>{this.child1=ref;}; 第三步 Child2組件觸發一個事件的時候,就可以直接這樣調用this.child1.onChange(),Child1組件里面就會直接調用onChange函數,修改text為Child1 onChange;

到這里就可以實現調用兄弟組件,其實還是用父組件做了中間傳遞。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持錯新站長站。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 沅陵县| 上虞市| 武强县| 陈巴尔虎旗| 绍兴县| 阿拉善盟| 建昌县| 广南县| 应用必备| 青龙| 曲沃县| 陆良县| 巍山| 彭泽县| 化州市| 长宁县| 蒲城县| 水城县| 峡江县| 辽宁省| 昔阳县| 兴山县| 遵化市| 靖安县| 廉江市| 元朗区| 绍兴市| 桐柏县| 类乌齐县| 高淳县| 柳江县| 绥芬河市| 昌乐县| 尖扎县| 当雄县| 镇雄县| 长宁区| 寿宁县| 金华市| 天镇县| 营口市|