父组件:
import React, { Component } from 'react';
import Child from './child2'
class Parents extends Component {
constructor(props) {
super(props);
this.state = {
parentValue: '这是父组件传给子组件的值'
}
}
getValue(val) {
console.log(val)
}
render() {
return (
<section>
<Child getValue={(value) => { this.getValue(value) }} parentValue={this.state.parentValue} handleCancel={this.handleCancel} onRef={(ref) => { this.child = ref }}></Child>
</section>
);
}
}
export default Parents;
子组件:
import React, { Component } from 'react';
class Child extends Component {
constructor(props) {
super(props);
}
valueToParent() {
this.props.getValue('666')
}
render() {
return (
<section style={{ border: '1px solid red', padding: '20px', margin: '20px' }} className="childWrap">
<div>{this.props.parentValue}</div>
<button onClick={(e) => { this.valueToParent(e) }}>子组件向父组件传值</button>
</section>
);
}
}
export default Child;
这篇博客介绍了React中父子组件间的通信方式。父组件通过props向子组件传递值,并通过定义回调函数实现子组件向父组件传递值的功能。示例代码展示了如何在子组件中触发父组件的方法,以及如何接收和处理子组件传回的值。

3282

被折叠的 条评论
为什么被折叠?



