当前位置:首页 > 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传递给子组件。

react父子组件如何调用

// 父组件
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逐层传递。

react父子组件如何调用

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>
    </>
  );
}

状态提升模式

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

// 父组件
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中实现动画效果,可以通过以下组件和方法实现: Vue内置动画组件 Vue提供了<transition>和<transition-group>两个内置组件,用于处理进…

vue怎么实现组件缓存

vue怎么实现组件缓存

vue实现组件缓存的方法 在Vue中实现组件缓存可以通过内置的<keep-alive>组件完成,该组件能够缓存不活动的组件实例,避免重复渲染。 使用<keep-alive>…

uniapp组件写法

uniapp组件写法

Uniapp 组件的基本写法 Uniapp 的组件写法与 Vue 类似,支持单文件组件(.vue 文件)。一个基本的组件通常包含三个部分:<template>、<script>…

vue 实现组件刷新

vue 实现组件刷新

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

vue抽屉组件实现

vue抽屉组件实现

Vue 抽屉组件实现 使用 Element UI 实现 Element UI 提供了现成的抽屉组件 el-drawer,可以快速实现抽屉效果。 安装 Element UI: npm install…

vue 组件实现 遮罩

vue 组件实现 遮罩

Vue 组件实现遮罩层的方法 基础遮罩层实现 创建一个简单的遮罩层组件,使用绝对定位覆盖整个视口。以下是一个基础实现: <template> <div class="mask…