-
父组件 ----》子组件
(1)、父组件中调用子组件的时候,直接将值传递给子组件;//数据状态 一个数据为对象 一个数据为字符串类型 this.state = { transValue:{ name:"小徐", age:'23', idol:'一宝' }, params:'我是父组件的数据' }
//调用子组件并且传值 render() { const {transValue, params} = this.state; return ( <div className="app-container"> <Count transValue={transValue} params={params} ></Count> </div> ) }
(2)、在子组件中接收父组件传递过来的数据
const {transValue, params} = this.props; console.log("我是父组件传递过来的数据哇!!!"); console.log(transValue); console.log(params);
在这里我们主要学习到了:
1)、父组件传递给子组件的值,通过props来获取
2)、从父组件传递过来的数据,在子组件中修改,如果该数据是对象,则可以修改,并将负组 件中的数据一并修改;
3)、如果该数据是字符串等简单类型,则不可以修改该数据;
-
子组件 ----》父组件
(1)、在父组件中定义一个函数(带有参数)并传递给子组件;transToParent = (value)=>{ console.log(value) }
<Count transToParent = {this.transToParent}></Count>
(2)、子组件接收父组件传递过来的函数
const {transToParent} = this.props;
<button onClick={()=>{transToParent(count)}}>点击传递count</button> <button onClick={()=>{transToParent(countObj)}}>点击传递countObj</button>
(3)、父组件接收子组件传递过来的参数
最基本的父子组件传值就已经讲述完毕;