react父子组件如何调用
父子组件通信方法
父组件向子组件传递数据 通过props传递数据给子组件,子组件通过this.props接收。
父组件代码示例:
<ChildComponent message="Hello from Parent" />
子组件代码示例:
class ChildComponent extends React.Component {
render() {
return <div>{this.props.message}</div>;
}
}
子组件向父组件传递数据 通过回调函数实现,父组件将函数作为prop传递给子组件,子组件调用该函数。
父组件代码示例:
handleChildData = (data) => {
console.log(data);
}
<ChildComponent onDataReceived={this.handleChildData} />
子组件代码示例:
<button onClick={() => this.props.onDataReceived('Data from Child')}>
Send Data
</button>
使用ref访问子组件 父组件可以通过ref直接调用子组件的方法。
父组件代码示例:
class ParentComponent extends React.Component {
childRef = React.createRef();
handleClick = () => {
this.childRef.current.childMethod();
}
render() {
return (
<>
<ChildComponent ref={this.childRef} />
<button onClick={this.handleClick}>Call Child Method</button>
</>
);
}
}
子组件代码示例:
class ChildComponent extends React.Component {
childMethod = () => {
console.log('Child method called');
}
render() {
return <div>Child Component</div>;
}
}
使用Context跨层级通信 当组件层级较深时,可以使用Context避免props层层传递。
创建Context:
const MyContext = React.createContext();
父组件提供值:
<MyContext.Provider value={sharedValue}>
<ChildComponent />
</MyContext.Provider>
子组件消费值:
<MyContext.Consumer>
{value => <div>{value}</div>}
</MyContext.Consumer>
使用自定义事件 可以通过事件总线或自定义事件实现更灵活的通信。
创建事件总线:
const EventBus = new EventEmitter();
父组件监听事件:
componentDidMount() {
EventBus.on('childEvent', this.handleChildEvent);
}
componentWillUnmount() {
EventBus.off('childEvent', this.handleChildEvent);
}
子组件触发事件:

EventBus.emit('childEvent', eventData);






