react組件傳值的方式大全


組件傳值的分類

1.按嵌套關系分:父子傳值和兄弟傳值(意思是指跨組件傳值)
1.按傳值方法分:props,ref,context,updater,redux

一.父子傳值

1.向下傳值--父組件向子組件傳值
父組件通過props傳遞一個不是方法的數據,給子組件;

//父組件中
<Child data={[1,2,3]} />
//子組件中
console.log(this.props.data);

2.向上傳值--子組件向父組件傳值
父組件通過props向子組件傳入一個方法,子組件在通過調用該方法,並將數據以參數的形式傳給父組件,父組件可以在該方法中對傳入的數據進行處理;

//父組件
import Child from './Child.js';
export default class Parent extend compenent{
  getData=(data)=>{
    console.log(data);
  }
  render(){
    return (
      <div>
        父組件
        <Child getData={this.getData}/>
      </div>
    )
  }
}

//子組件
export default class Child extend compenent{
  state={
    data:[1,2,3]
  }
  render(){
    const {data}=this.state;
    return (
      <div>
        子組件
        <button onClick={()=>{this.props.getData(data)}}><button>
      </div>
    )
  }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM