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

首頁 > 語言 > JavaScript > 正文

react 組件傳值的三種方法

2024-05-06 15:38:31
字體:
供稿:網(wǎng)友

整理 react 組件傳值 三種方式

父組件向子組件傳值(通過props傳值)

子組件:

  class Children extends Component{    constructor(props){      super(props);    }    render(){      return(        <div>這是:{this.props.name}</div> // 這是 父向子      )    }  }

父組件:

  class App extends React.Component{    render(){      return(        <div>          <Children name="父向子"/>        </div>      )    }  }

父組件向子組件傳值(回調(diào)函數(shù))

子組件

  class Children extends Component{    constructor(props){      super(props);    }    handerClick(){      this.props.changeColor('skyblue') // 執(zhí)行父組件的changeColor 并傳參 必須和父組件中的函數(shù)一模一樣    }    render(){      return(        <div>          <div>父組件的背景色{this.props.bgcolor}</div> // 子組件接收父組件傳過來的值 bgcolor          <button onClick={(e)=>{this.handerClick(e)}}>改變父組件背景</button> // 子組件執(zhí)行函數(shù)        </div>      )    }  }

父組件

  class Father extends Component{    constructor(props){      super(props)      this.state = {        bgcolor:'pink'      }    }    bgChange(color){      this.setState({        bgcolor:color      })    }    render(props){      <div style={{background:this.state.bgcolor}}>              // 給子組件傳遞的值 color         <Children bgcolor={this.state.bgcolor} changeColor={(color)=>{this.bgChange(color)}} />                           // changeColor 子組件的參數(shù)=color 當(dāng)做形參      </div>    }  }

兄弟組件傳值(子傳給父,父再傳給另一個(gè)子)

子組件1

  class Children1 extends Component{    constructor(props){      super(props);    }    handerClick(){      this.props.changeChild2Color('skyblue')       // 改變兄弟組件的顏色 把changeChild2Color的參數(shù)傳給父    }    render(){      return(        <div>          <div>children1</div>          <button onClick={(e)=>{this.handerClick(e)}}>改變children2背景</button>        </div>      )    }  }

子組件2

  class Children2 extends Component{    constructor(props){      super(props);    }    render(){      return(        <div style={{background:this.props.bgcolor}}>        // 從父元素獲取自己的背景色          <div>children2 背景色 {this.props.bgcolor}</div>          // children2 背景色 skyblue        </div>      )    }  }  

父組件

class Father extends Component{  constructor(props){    super(props)    this.state = {      child2bgcolor:'pink'    }  }  onchild2bgChange(color){    this.setState({      child2bgcolor:color    })  }  render(props){    <div>      <Children1 changeChild2Color={(color)=>{this.onchild2bgChange(color)}} />      <Children2 bgcolor={this.state.child2bgcolor} />    </div>  }}            
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 手游| 宁陵县| 闽侯县| 中山市| 准格尔旗| 喀喇沁旗| 道真| 汶上县| 石嘴山市| 九江县| 黑水县| 宁德市| 汝州市| 中方县| 高州市| 池州市| 顺平县| 海晏县| 涟源市| 辽阳市| 建水县| 启东市| 伊宁县| 阜城县| 赣榆县| 商都县| 同德县| 宾川县| 桃园市| 新竹市| 前郭尔| 固始县| 土默特左旗| 义马市| 泰兴市| 云梦县| 仙桃市| 思南县| 龙里县| 丘北县| 海安县|