1.父组件传数据给子组件
父组件传数据给子组件是用props来实现的,子组件内部调用this.props.xx来获取传递的值,这个值在子组件内部一般只用作展示用,最好不要在子组件中进行修改。
父组件
<ChildComponent ChildName="don"/>
子组件
import React from 'react';
class ChildComponent extends React.Component{
render(){
return(
<React.Fragment>
从父组件传过来的值是{this.props.ChildName}
</React.Fragment>
)
}
}
export default ChildComponent;
2.子组件传递数据给父组件
子组件传递数据给父组件是通过事件传参实现的,调用父组件传过来的事件的同时将数据作为参数返回给父组件。
父组件
...
introduce(valFromChild){
console.log(`从子组件传过来的值是${valFromChild}`)
}
render(){
return (
<React.Fragment>
<ChildComponent
IntroduceFn = {this.introduce}/>
</React.Fragment>
)
}
...
子组件
<React.Fragment>
<button onClick={this.props.IntroduceFn.bind(this,"hello")}>点击</button>
</React.Fragment>
子组件点击后调用IntroduceFn
并将"hello"作为参数返回,父组件触发introduce
方法后就可以从参数中获取子组件传过来的值了。
网友评论