当前位置:首页 > React

react父子组件如何传值

2026-01-25 04:33:36React

React 父子组件传值方法

父组件向子组件传值(Props)

父组件通过属性(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>;
}

子组件向父组件传值(回调函数)

父组件通过传递回调函数给子组件,子组件调用该函数并传递数据。

父组件代码示例:

react父子组件如何传值

import ChildComponent from './ChildComponent';

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

子组件代码示例:

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

使用 Context API 跨层级传值

适用于深层嵌套组件传值,避免逐层传递 props。

创建 Context:

react父子组件如何传值

import { createContext, useContext } from 'react';

const MyContext = createContext();

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

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

使用 Refs 访问子组件

父组件通过 ref 直接调用子组件方法或访问其状态。

父组件代码示例:

import { useRef } from 'react';
import ChildComponent from './ChildComponent';

function ParentComponent() {
  const childRef = useRef();

  const getChildData = () => {
    alert(childRef.current.getValue());
  };

  return (
    <>
      <ChildComponent ref={childRef} />
      <button onClick={getChildData}>Get Child Data</button>
    </>
  );
}

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

import { forwardRef, useImperativeHandle } from 'react';

const ChildComponent = forwardRef((props, ref) => {
  useImperativeHandle(ref, () => ({
    getValue: () => "Data from Child"
  }));

  return <div>Child Component</div>;
});

每种方法适用于不同场景,根据组件关系和需求选择合适的方式。简单父子通信推荐使用 props 和回调函数,深层嵌套组件可考虑 Context API,需要直接访问子组件时使用 refs。

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

相关文章

vue实现组件封装

vue实现组件封装

Vue 组件封装方法 封装组件的基本步骤 创建独立的 .vue 文件,包含 template、script 和 style 三个部分。通过 props 接收父组件传递的数据,使用 $emit 触发…

vue实现tooltips组件

vue实现tooltips组件

Vue实现Tooltips组件的方法 基础实现:使用Vue指令 创建一个自定义指令v-tooltip,通过鼠标事件触发提示框的显示与隐藏。 Vue.directive('tooltip', {…

vue怎么实现组件缓存

vue怎么实现组件缓存

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

uniapp组件写法

uniapp组件写法

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

vue实现拖拽实现组件嵌套

vue实现拖拽实现组件嵌套

实现拖拽组件嵌套的核心思路 Vue中实现拖拽组件嵌套需要结合拖拽库(如vuedraggable)和组件递归渲染。核心在于动态管理嵌套数据结构,并通过事件传递实现层级更新。 安装必要依赖 推荐使用v…

uniapp 分页组件

uniapp 分页组件

uniapp 分页组件实现方法 在uniapp中实现分页功能,可以通过自定义组件或使用第三方组件库完成。以下是几种常见实现方式: 自定义分页组件 创建一个名为uni-pagination的组件,模板…