当前位置:首页 > React

react组件如何传递参数

2026-03-11 05:17:23React

传递 props 给子组件

在父组件中通过属性名直接传递数据,子组件通过 props 对象接收。例如父组件传递 nameage

<ChildComponent name="Alice" age={25} />

子组件通过解构或直接访问 props 使用:

function ChildComponent(props) {
  return <div>{props.name} is {props.age} years old</div>;
}
// 或解构
function ChildComponent({ name, age }) {
  return <div>{name} is {age} years old</div>;
}

动态传递 props

通过变量或表达式动态传递值。例如从父组件状态传递数据:

function ParentComponent() {
  const [user, setUser] = useState({ name: "Bob", age: 30 });
  return <ChildComponent name={user.name} age={user.age} />;
}

传递整个对象

使用展开运算符批量传递对象的属性:

const user = { name: "Charlie", age: 35 };
<ChildComponent {...user} />

传递函数

将父组件的函数作为回调传递给子组件:

function ParentComponent() {
  const handleClick = () => console.log("Clicked");
  return <ChildComponent onClick={handleClick} />;
}

function ChildComponent({ onClick }) {
  return <button onClick={onClick}>Click Me</button>;
}

使用 Context 跨层级传递

通过 React Context 实现深层组件参数传递:

const UserContext = createContext();

function App() {
  return (
    <UserContext.Provider value={{ name: "Dave", age: 40 }}>
      <DeepChildComponent />
    </UserContext.Provider>
  );
}

function DeepChildComponent() {
  const user = useContext(UserContext);
  return <div>{user.name}</div>;
}

通过 children 传递内容

使用 props.children 传递组件之间的嵌套内容:

function ParentComponent() {
  return (
    <ChildComponent>
      <div>This content is passed as children</div>
    </ChildComponent>
  );
}

function ChildComponent({ children }) {
  return <div className="container">{children}</div>;
}

使用 Render Props 模式

通过函数 prop 共享组件间的代码:

react组件如何传递参数

function MouseTracker(props) {
  const [position, setPosition] = useState({ x: 0, y: 0 });
  return props.render(position);
}

function App() {
  return (
    <MouseTracker render={({ x, y }) => (
      <div>Mouse at ({x}, {y})</div>
    )} />
  );
}

标签: 组件参数
分享给朋友:

相关文章

vue实现组件循环

vue实现组件循环

Vue 实现组件循环的方法 在 Vue 中,可以通过 v-for 指令实现组件的循环渲染。以下是几种常见的实现方式: 使用 v-for 渲染数组 通过 v-for 遍历数组数据,动态生成组件列表:…

vue动态组件实现

vue动态组件实现

动态组件的基本用法 在Vue中,动态组件通过<component>标签和is属性实现。is属性可以绑定组件名称或组件选项对象,实现动态切换。 <template> <…

react参数如何传递

react参数如何传递

参数传递方式 React 中参数传递主要有以下几种方式: Props 传递 父组件通过属性(props)向子组件传递数据。子组件通过 props 对象接收参数。 // 父组件 <Chil…

vue实现秒表组件

vue实现秒表组件

实现秒表组件的基本思路 使用Vue实现秒表组件需要管理时间状态、控制计时器的启动/暂停/重置功能,并通过计算属性动态显示格式化时间。核心逻辑包括利用setInterval更新计时数据,并通过生命周期钩…

vue实现分页组件

vue实现分页组件

Vue 分页组件实现 基础分页组件结构 创建一个名为 Pagination.vue 的文件,包含以下基础模板和逻辑: <template> <div class="pagina…

vue实现高阶组件

vue实现高阶组件

Vue 高阶组件实现方法 高阶组件(HOC)是一种复用组件逻辑的模式,通过函数包裹组件并返回新组件实现。Vue 中可通过以下方式实现: 使用 render 函数 通过函数接收组件选项并返回新组件选项…