当前位置:首页 > React

react父子组件如何传值

2026-03-11 13:40:06React

父组件向子组件传值

父组件通过props向子组件传递数据。在父组件中,将数据作为属性传递给子组件,子组件通过props接收这些数据。

父组件代码示例:

import ChildComponent from './ChildComponent';

function ParentComponent() {
  const message = "Hello from Parent";
  return <ChildComponent message={message} />;
}

子组件代码示例:

function ChildComponent(props) {
  return <div>{props.message}</div>;
}

子组件向父组件传值

子组件通过调用父组件传递的回调函数向父组件传递数据。父组件定义一个函数,将其作为prop传递给子组件,子组件在需要时调用该函数并传递数据。

父组件代码示例:

import ChildComponent from './ChildComponent';

function ParentComponent() {
  const handleData = (data) => {
    console.log("Data from child:", data);
  };
  return <ChildComponent onData={handleData} />;
}

子组件代码示例:

function ChildComponent(props) {
  const sendData = () => {
    props.onData("Data from Child");
  };
  return <button onClick={sendData}>Send Data</button>;
}

使用Context跨层级传值

对于深层嵌套的组件,可以使用React Context避免props层层传递。创建Context后,父组件作为Provider提供数据,子组件通过Consumer或useContext获取数据。

创建Context:

const MyContext = React.createContext();

父组件代码示例:

function ParentComponent() {
  const value = "Shared Value";
  return (
    <MyContext.Provider value={value}>
      <ChildComponent />
    </MyContext.Provider>
  );
}

子组件代码示例(使用useContext):

function ChildComponent() {
  const value = React.useContext(MyContext);
  return <div>{value}</div>;
}

使用Ref获取子组件实例

父组件可以通过ref获取子组件实例,直接调用子组件的方法或访问其状态。需要子组件是类组件或使用forwardRef包装的函数组件。

父组件代码示例:

import ChildComponent from './ChildComponent';

function ParentComponent() {
  const childRef = React.useRef();
  const handleClick = () => {
    childRef.current.doSomething();
  };
  return (
    <>
      <ChildComponent ref={childRef} />
      <button onClick={handleClick}>Call Child Method</button>
    </>
  );
}

子组件代码示例(使用forwardRef):

react父子组件如何传值

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

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

相关文章

vue实现多级组件

vue实现多级组件

Vue 多级组件实现方法 在 Vue 中实现多级组件通常涉及父子组件通信、动态组件或递归组件等技术。以下是几种常见实现方式: 父子组件嵌套 通过逐层嵌套组件实现多级结构,适用于固定层级场景: &l…

vue radio组件实现

vue radio组件实现

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

vue实现路由组件

vue实现路由组件

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

vue实现搜索组件

vue实现搜索组件

Vue 实现搜索组件的方法 基础搜索组件实现 创建基础搜索组件需要包含输入框和搜索按钮。在Vue中可以使用v-model绑定输入值,通过@click或@keyup.enter触发搜索。 <te…

vue实现组件递归

vue实现组件递归

递归组件的实现方法 在Vue中实现递归组件,核心是通过组件在自身模板中调用自身。需要明确递归终止条件以避免无限循环。 定义递归组件 给组件设置name选项,便于在模板中自引用: export de…

vue实现tab组件

vue实现tab组件

Vue实现Tab组件的核心方法 使用动态组件与v-for结合 通过v-for渲染标签头,结合v-model控制当前激活的标签页。模板部分可设计为: <div class="tabs">…