前言:
React是单向数据流,当有多个组件需要共享状态的时候,这就需要把状态放到这些组件共有的父组件中,相应地,这些组件就变成了子组件,从而涉及到父子组件之间的通信。父组件通过props 给子组件传递数据,子组件则是通过调用父组件传给它的函数给父组件传递数据。
父组件 App.js
import React, { Component } from 'react';
import Child from './child'
class App extends Component {
constructor(props){
super(props);
this.state={
msg:'父类的消息',
name:'John',
age:50
};
this.callback = this.callback.bind(this);
}
callback(msg,name,age){
this.setState({msg});
this.setState({name});
this.setState({age});
}
render() {
return (
<div className="App">
<p> Message: {this.state.msg}</p>
<Child callback={this.callback} age={this.state.age} name={this.state.name}>
</Child>
</div>
);
}
}
export default App;
父组件给子组件传值方式,通过props方式,传递两个属性,age、name,一个方法callback:
<Child callback={this.callback} age={this.state.age} name={this.state.name}></Child>
子组件 Clild.js
import React from "react";
class Child extends React.Component{
constructor(props){
super(props);
this.state={
name:'Andy',
age:20,
msg:"来自子类的消息"
};
this.change = this.change.bind(this);
}
change(){
//调用父组件的方法修改父组件的内容
this.props.callback(this.state.msg,this.state.name,this.state.age);
}
render(){
return(
<div>
<div>{this.props.name}</div>
<div>{this.props.age}</div>
<button onClick={this.change}>点击</button>
</div>
)
}
}
export default Child;
这里调用组件方法时需要注意this的指向,可通过以下两种方法(不限于)改变this指向:
1、使用bind方法:bind返回一个方法,传参第一个参数为this的目标指向,第二个及以后的参数为原函数的参数。
2、使用箭头函数:例如父组件中callback方法的定义:
callback=(msg,name,age)=>{
this.setState({msg});
this.setState({name});
this.setState({age});
}