
在react中父子组件传参
一 、父传子

子组件把值传给父组件
在父组件中 其实可以把子组件里的方法用箭头函数,这样就不要绑定this了
export default class Son extends Component {
static propTypes = {
};
gaibian=()=>{
let aaa={name:"guining",age:22};
console.log(this)
this.props.change(aaa)
}


在子组件中

代码如下
//父组件的代码
export class Text extends Component {
static propTypes = {
test: PropTypes.object.isRequired,
actions: PropTypes.object.isRequired,
};
state={
list:{name:'libin',age:18}
}
change=(zhi)=>{
let {list} = this.state;
if(zhi==={}){
console.log('值不能为空')
}
this.setState({
list:zhi
})
}
render() {
let {list} = this.state;
return (
<div className="test-text">
父组件
<Son List={list} change={this.change} ></Son>
</div>
);
}
}
//子组件的代码
export default class Son extends Component {
static propTypes = {
};
constructor(props){
super(props);
this.gaibian=this.gaibian.bind(this)
}
gaibian(){
let aaa={name:"guining",age:22};
console.log(this)
this.props.change(aaa)
}
render() {
let {List} = this.props;
console.log(List)
return (
<div className="test-son">
子组件
<p>姓名:{List.name}</p>
<p>年龄:{List.age}岁</p>
<button onClick={this.gaibian}>改变</button>
</div>
);
网友评论