当前位置:首页 > 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组件是Vue.js的核心概念之一,用于构建可复用的UI模块。以下是Vue组件的几种常见实现方式: 单文件组件(SFC) 使用.vue文件格式,将模板、脚本和样式封装…

vue实现组件封装

vue实现组件封装

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

vue radio组件实现

vue radio组件实现

Vue Radio 组件实现 在 Vue 中实现 Radio 组件可以通过原生 HTML 的 <input type="radio"> 结合 Vue 的响应式特性,或者使用第三方 UI 库…

vue怎么实现组件缓存

vue怎么实现组件缓存

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

vue实现倒计时组件

vue实现倒计时组件

Vue 倒计时组件实现 核心思路 通过 setInterval 或 setTimeout 实现时间递减,结合 Vue 的响应式数据更新 UI。需注意组件销毁时清除定时器。 基础实现方案 模板部分…

vue实现下拉刷新组件

vue实现下拉刷新组件

Vue 下拉刷新组件实现 核心思路 通过监听 touch 事件计算滑动距离,结合 CSS 过渡动画实现下拉效果,触发刷新回调。 基础实现步骤 监听 touch 事件 在组件 mounted 阶段绑定…