当前位置:首页 > 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>;
}

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

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

父组件代码示例:

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:

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):

react父子组件如何传值

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。

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

相关文章

uniapp组件写法

uniapp组件写法

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

uniapp 分页组件

uniapp 分页组件

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

vue实现组件刷新

vue实现组件刷新

强制重新渲染组件 使用 this.$forceUpdate() 方法可以强制 Vue 实例重新渲染,但不会更新子组件。适用于依赖非响应式数据的情况。 methods: { refreshComp…

vue缩放组件实现

vue缩放组件实现

Vue 缩放组件实现方法 基于 CSS transform 实现缩放 通过 CSS 的 transform: scale() 属性实现基础缩放效果。在 Vue 中动态绑定 scale 值,结合鼠标事…

vue父子组件实现

vue父子组件实现

Vue 父子组件通信实现 Vue 父子组件通信主要通过 props 和 events 实现,父组件向子组件传递数据使用 props,子组件向父组件传递数据使用自定义事件。 父组件向子组件传递数据 父…

vue实现loading组件

vue实现loading组件

Vue 实现 Loading 组件的方法 基础实现方案 创建一个独立的 Loading.vue 组件文件: <template> <div v-if="isLoading" c…