当前位置:首页 > React

react父子组件如何调用

2026-01-24 10:59:11React

父子组件通信方法

父组件向子组件传递数据可以通过props实现。父组件在渲染子组件时,将数据作为属性传递给子组件。

// 父组件
function Parent() {
  const data = "Hello from parent";
  return <Child message={data} />;
}

// 子组件
function Child({ message }) {
  return <div>{message}</div>;
}

子组件向父组件通信

子组件通过调用父组件传递的回调函数来实现通信。父组件定义一个函数并通过props传递给子组件。

// 父组件
function Parent() {
  const handleChildEvent = (data) => {
    console.log(data);
  };
  return <Child onEvent={handleChildEvent} />;
}

// 子组件
function Child({ onEvent }) {
  const sendData = () => {
    onEvent("Data from child");
  };
  return <button onClick={sendData}>Send</button>;
}

使用Context跨层级通信

当组件层级较深时,可以使用React Context来避免props逐层传递。

const MyContext = React.createContext();

// 父组件
function Parent() {
  const value = "Shared data";
  return (
    <MyContext.Provider value={value}>
      <Child />
    </MyContext.Provider>
  );
}

// 子组件
function Child() {
  const contextValue = React.useContext(MyContext);
  return <div>{contextValue}</div>;
}

使用Ref直接调用子组件方法

父组件可以通过ref直接调用子组件的方法,适用于需要直接操作子组件的情况。

// 子组件
const Child = React.forwardRef((props, ref) => {
  React.useImperativeHandle(ref, () => ({
    childMethod: () => {
      console.log("Child method called");
    }
  }));
  return <div>Child Component</div>;
});

// 父组件
function Parent() {
  const childRef = React.useRef();
  const callChildMethod = () => {
    childRef.current.childMethod();
  };
  return (
    <>
      <Child ref={childRef} />
      <button onClick={callChildMethod}>Call Child Method</button>
    </>
  );
}

状态提升模式

当多个子组件需要共享状态时,可以将状态提升到最近的共同父组件中。

react父子组件如何调用

// 父组件
function Parent() {
  const [count, setCount] = React.useState(0);
  return (
    <>
      <ChildA count={count} />
      <ChildB onIncrement={() => setCount(c => c + 1)} />
    </>
  );
}

// 子组件A
function ChildA({ count }) {
  return <div>Count: {count}</div>;
}

// 子组件B
function ChildB({ onIncrement }) {
  return <button onClick={onIncrement}>Increment</button>;
}

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

相关文章

vue 实现组件刷新

vue 实现组件刷新

实现组件刷新的方法 在Vue中,组件刷新通常指重新渲染组件或重置组件状态。以下是几种常见的实现方式: 使用v-if控制渲染 通过v-if指令可以销毁并重新创建组件: <template>…

vue实现下拉框组件

vue实现下拉框组件

Vue 下拉框组件实现 基础实现 创建基础下拉框组件,使用v-model实现双向数据绑定: <template> <div class="dropdown"> &…

vue radio组件实现

vue radio组件实现

Vue Radio 组件实现 在 Vue 中实现 Radio 组件可以通过原生 HTML 的 <input type="radio"> 结合 Vue 的响应式特性来完成。以下是几种常见的实…

vue实现tooltips组件

vue实现tooltips组件

实现基础 Tooltip 组件 创建一个名为 Tooltip.vue 的单文件组件,包含模板、样式和逻辑: <template> <div class="tooltip-con…

vue 实现组件刷新

vue 实现组件刷新

组件局部刷新 在Vue中实现组件刷新可以通过强制重新渲染组件来实现。常用的方法有以下几种: 使用v-if指令 通过切换v-if条件触发组件的销毁和重建 <template> <…

如何缓存react组件

如何缓存react组件

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