当前位置:首页 > 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对象,提取需要的属性:

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

默认参数设置

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

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

传递多个参数

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

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可以传递组件之间的嵌套内容:

react函数组件如何传参

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

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

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

相关文章

vue table组件实现

vue table组件实现

Vue 表格组件实现方案 基础表格实现 使用<table>标签结合v-for指令渲染数据是最简单的实现方式: <template> <table> &…

vue 实现toast组件

vue 实现toast组件

实现 Vue Toast 组件的方法 创建基础 Toast 组件 在 Vue 项目中创建一个基础 Toast 组件,通常包含消息内容和显示控制逻辑。 <template> <d…

vue 动态组件实现

vue 动态组件实现

vue 动态组件实现 Vue 的动态组件功能允许根据条件或用户交互动态切换不同的组件,主要通过 <component> 标签和 is 属性实现。 基本用法 通过 is 属性绑定组件名或组…

vue实现表格组件

vue实现表格组件

Vue 表格组件实现方法 基础表格实现 使用 Vue 的模板语法可以快速实现基础表格功能。通过 v-for 指令循环渲染表格数据。 <template> <table>…

vue组件实现动画

vue组件实现动画

Vue 组件实现动画的方法 Vue 提供了多种方式实现组件动画,主要包括内置的 <transition> 和 <transition-group> 组件,以及结合 CSS 或…

vue实现tab组件

vue实现tab组件

Vue实现Tab组件的核心方法 使用动态组件与v-for结合 通过v-for渲染标签头,结合v-model控制当前激活的标签页。模板部分可设计为: <div class="tabs">…