当前位置:首页 > 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 中实现组件可以通过多种方式,包括全局注册、局部注册、单文件组件(SFC)等。以下是常见的实现方法。 全局注册组件 全局注册的组件可以在任何 Vue 实例或组件中使用。…

如何缓存react组件

如何缓存react组件

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

vue实现路由组件

vue实现路由组件

Vue 实现路由组件的方法 在 Vue 中实现路由功能通常需要结合 Vue Router 库,以下是具体实现步骤: 安装 Vue Router 通过 npm 或 yarn 安装 Vue Router…

vue实现列表组件

vue实现列表组件

Vue 列表组件实现方法 基础列表渲染 使用 v-for 指令渲染数组数据,需配合 :key 提升性能: <template> <ul> <li v-for…

vue 实现树组件

vue 实现树组件

Vue 树形组件实现 基础树形结构实现 使用递归组件实现树形结构,核心是通过组件自身调用自身渲染嵌套数据。 <template> <ul> <li v-fo…

vue实现附件组件

vue实现附件组件

Vue 实现附件组件的方法 基础组件结构 使用 Vue 的单文件组件(SFC)方式创建一个基础的附件上传组件。需要包含文件选择、预览、上传和删除功能。 <template> <…