当前位置:首页 > React

react父子组件如何调用

2026-03-10 19:18:40React

父子组件通信方法

父组件向子组件传递数据 通过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);
}

子组件触发事件:

react父子组件如何调用

EventBus.emit('childEvent', eventData);

标签: 父子组件
分享给朋友:

相关文章

vue实现下拉刷新组件

vue实现下拉刷新组件

Vue 下拉刷新组件实现 核心思路 通过监听 touch 事件计算滑动距离,结合 CSS 过渡动画实现下拉效果,触发刷新回调。 基础实现步骤 监听 touch 事件 在组件 mounted 阶段绑定…

vue table组件实现

vue table组件实现

Vue 表格组件实现方案 基础表格实现 使用<table>标签结合v-for指令渲染数据是最简单的实现方式: <template> <table> &…

vue实现水印组件

vue实现水印组件

Vue 水印组件的实现方法 使用Canvas绘制水印 在Vue组件中通过Canvas动态生成水印图案,将其作为背景添加到目标元素上。 <template> <div ref="…

如何缓存react组件

如何缓存react组件

缓存React组件的方法 React.memo 使用React.memo对函数组件进行浅比较缓存,避免不必要的重新渲染。适用于props不变的场景。 const MemoizedComponen…

vue实现组件切换

vue实现组件切换

Vue 组件切换的实现方法 在 Vue 中实现组件切换有多种方式,以下是几种常见的方法: 动态组件 使用 Vue 内置的 <component> 元素和 is 属性可以动态切换组件:…

vue实现search组件

vue实现search组件

Vue 实现搜索组件 基础实现 创建一个基础的搜索组件需要包含输入框和搜索逻辑。以下是一个简单的实现示例: <template> <div class="search-cont…