react子组件向父组件传值
// 父组件
class App extends Component {
constructor(props) {
super(props)
this.state = {
test: '123'
};
}
parentClick(arg) {
this.setState({
test: arg
})
}
render() {
return (
<div>
<div>我是父组件</div>
{this.state.test}
<Child parentClick={this.parentClick.bind(this)}/>
</div>
);
}
}
//子组件
class Child extends Component {
handClick() {
this.props.parentClick('345')
}
render() {
return (
<div>
<button onClick={this.handClick.bind(this)}>子组件</button>
</div>
);
}
}
[外链图片转存失败(img-AM6PjvDR-1563848542807)(C:\Users\QJ\AppData\Local\Temp\1563593037683.png)]
-
若子组件想要改变父组件的值,在父组件定义一个事件并传给子组件。
-
子组件通过点击按钮调用父组件定义的事件,并将需要传递的值作为参数。
-
在父组件事件中处理数据。
跨级组件之间传递数据
-
使用context (基于生产者-消费者模型)
//App import React, {Component} from 'react' import Child from './child' import PropTypes from 'prop-types' import './index.css'; class App extends Component { constructor(props) { super(props) this.state = { test: '123' }; } //父组件声明自己支持的context static childContextTypes = { foo: PropTypes.string, test: PropTypes.string, parentClick: PropTypes.func }; //父组件提供一个函数,用来返回相应的 context 对象 getChildContext() { return { foo: 'bar', test: this.state.test, parentClick: this.parentClick.bind(this) } } parentClick(arg) { this.setState({ test: arg }) } render() { return ( <div> <div>我是父组件</div> {this.state.test} <Child parentClick = {this.parentClick.bind(this)}/> </div> ); } } export default App
// Child import React, {Component} from 'react' import Grandson from './grandson' class Child extends Component { handClick() { this.props.parentClick('345') } render() { return ( <div> <button onClick={this.handClick.bind(this)}>子组件</button> <Grandson/> </div> ); } } export default Child
// Grandson import React, {Component} from 'react' import PropTypes from 'prop-types' class Grandson extends Component { // 孙子组件声明自己需要使用 context static contextTypes = { test: PropTypes.string, parentClick: PropTypes.func } handleClick(){ console.log(this.context); this.context.parentClick('789'); } render() { return ( <button onClick={this.handleClick.bind(this)}>孙子组件{this.context.test}</button> ); } } export default Grandson
使用context进行跨级传值:
- 设置context:
getChildContext
这个方法就是设置context
的过程,它返回的对象就是 context(也就是上图中处于中间的方块),所有的子组件都可以访问到这个对象。 - 设置
childContextTypes
:它的作用其实与propsType
验证组件props
参数的作用类似,必须设置 - 子组件获取context:contextTypes也是必写的,用来声明和验证你需要获取的状态的类型
- 声明后可通过this.context.XXX获取在App组件定义的context对象的属性。
- 设置context: