6. 组件间传参
- 父组件向子组件传参
- 子组件向父组件传参
具体代码可以参考我的github中的first-react
0. 上一波目前为止的App.js文件中我们的组件代码!
我们来回顾下之前我们做了啥,目前为止完整的代码:
import React, { Component } from 'react';
import './App.css';
class Header extends Component {
render() {
return <h1>Header</h1>;
}
}
class Content extends Component {
constructor(props) {
super(props);
this.state = {
content: '123',
count: 0
};
this.addCount = this.addCount.bind(this);
}
componentDidMount() {
const _this = this;
setTimeout(() => {
_this.setState({ content: 'change' });
// _this.state.content = 1;
}, 1000);
}
addCount() {
let count = this.state.count;
this.setState({
count: ++count
});
}
render() {
return (
<div>
<div>content:{this.state.content}</div>
<div>count: {this.state.count}</div>
<button onClick={this.addCount}>增加数量</button>
</div>
);
}
}
function App() {
return (
<div>
<Header />
<Content />
</div>
);
}
export default App;
1. 父组件向子组件传参
class Son extends Component {
constructor(props) {
super(props);
this.state = {
name: 'son'
};
}
clickBtn() {
this.props.callBack(this.state.name);
}
render() {
return (
<div>
<div>name:{this.props.name}</div>
<button onClick={this.clickBtn.bind(this)}>改变名称</button>
</div>
);
}
}
class Father extends Component {
constructor(props) {
super(props);
this.state = {
name: 'father'
};
}
callBack(name) {
this.setState({ name: name });
}
render() {
return (
<div>
<Son name={this.state.name} callBack={this.callBack.bind(this)} />
</div>
);
}
}
Notes:
- 父组件向子组件传参的方法: 在子组件标签上绑定“参数名=参数值”
- 在子组件中通过this.props.参数名拿到对应的父组件传过来的参数值
- 父组件中已经绑定父元素的this的函数也可以在子组件中得到调用
2. 子组件向父组件传参
从上面我们发现父组件可以将修改父组件内部参数的函数绑定父组件的this之后传递给子组件,实现子组件中的内容对父组件进行修改的过程。所以我们可以通过这个方法实现子组件向父组件的传参
class Son extends Component {
constructor(props) {
super(props);
this.state = {
name: 'son',
msg: 'Son Message'
};
this.sendMsg = this.sendMsg.bind(this);
}
clickBtn() {
this.props.callBack(this.state.name);
}
// 在子组件中通过this.props获取修改父组件的方法
sendMsg() {
this.props.msgFromChild(this.state.msg);
}
render() {
return (
<div>
<div>name:{this.props.name}</div>
<button onClick={this.clickBtn.bind(this)}>改变名称</button>
<br />
<button onClick={this.sendMsg}>发送信息</button>
</div>
);
}
}
class Father extends Component {
constructor(props) {
super(props);
this.state = {
name: 'father',
msg: ''
};
}
callBack(name) {
this.setState({ name: name });
}
// 通过子组件中传递过来的msg对父组件state的msg进行修改
msgFromChild(msg) {
this.setState({
msg: msg
});
}
render() {
return (
<div>
<div>Msg: {this.state.msg}</div>
<Son
name={this.state.name}
callBack={this.callBack.bind(this)}
msgFromChild={this.msgFromChild.bind(this)}
/>
</div>
);
}
}