当前位置:首页 > React

react函数组件如何传参

2026-01-26 03:00:21React

传递参数的方式

React函数组件可以通过props传递参数。父组件在调用子组件时,通过属性名传递数据,子组件通过函数的第一个参数(通常命名为props)接收。

父组件传递参数示例:

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

子组件接收参数示例:

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

解构props参数

在子组件中可以直接解构props对象,提取需要的属性:

react函数组件如何传参

function ChildComponent({ greeting }) {
  return <div>{greeting}</div>;
}

默认参数设置

可以为props参数设置默认值,当父组件未传递对应属性时使用:

function ChildComponent({ greeting = "Default greeting" }) {
  return <div>{greeting}</div>;
}

传递多个参数

父组件可以同时传递多个参数:

react函数组件如何传参

function ParentComponent() {
  return <ChildComponent 
           name="Alice" 
           age={25} 
           hobbies={['reading', 'swimming']} 
         />;
}

子组件接收多个参数:

function ChildComponent({ name, age, hobbies }) {
  return (
    <div>
      <p>Name: {name}</p>
      <p>Age: {age}</p>
      <p>Hobbies: {hobbies.join(', ')}</p>
    </div>
  );
}

传递函数作为参数

可以传递函数作为参数,实现子组件向父组件通信:

function ParentComponent() {
  const handleClick = () => {
    console.log('Button clicked in child');
  };

  return <ChildComponent onClick={handleClick} />;
}

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

使用children prop

通过props.children可以传递组件之间的嵌套内容:

function ParentComponent() {
  return (
    <ChildComponent>
      <p>This content will be passed as children</p>
    </ChildComponent>
  );
}

function ChildComponent({ children }) {
  return <div>{children}</div>;
}

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

相关文章

Vue函数实现

Vue函数实现

Vue 函数式组件的实现 Vue 函数式组件是一种无状态、无实例的组件形式,适用于简单渲染逻辑的场景。其核心特点是性能高效,适合纯展示型需求。 定义方式 export default { fu…

vue实现组件循环

vue实现组件循环

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

vue实现组件循环图片

vue实现组件循环图片

Vue 实现组件循环图片的方法 在 Vue 中实现组件循环图片通常可以通过 v-for 指令结合动态数据绑定完成。以下是几种常见的实现方式: 使用静态图片路径数组 假设有一组本地图片路径,可以通过数…

vue轮播组件实现

vue轮播组件实现

vue轮播组件实现方法 使用第三方库(如Swiper) 安装Swiper库: npm install swiper 在Vue组件中引入: <template> <div cl…

vue radio组件实现

vue radio组件实现

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

vue实现组件通信

vue实现组件通信

Vue 组件通信方法 Vue 提供了多种方式实现组件间的通信,适用于不同场景。以下是常见的方法: Props 和 Events 父组件通过 props 向子组件传递数据,子组件通过 $emit 触…