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

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

react组件如何传递参数

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} />

传递函数

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

react组件如何传递参数

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 共享组件间的代码:

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 下拉框组件实现 基础实现 创建基础下拉框组件,使用v-model实现双向数据绑定: <template> <div class="dropdown"> &…

uniapp如何将底部导航组件化

uniapp如何将底部导航组件化

在 uniapp 中将底部导航组件化 将底部导航组件化可以提高代码复用性和维护性。以下是具体实现方法: 创建自定义底部导航组件 新建一个组件文件,例如 tab-bar.vue,放置在 compon…

vue实现折叠组件

vue实现折叠组件

实现折叠组件的基本思路 在Vue中实现折叠组件通常需要利用动态绑定和条件渲染。核心是通过控制一个布尔值状态来决定内容是否显示,并添加过渡动画提升用户体验。 基础实现方法 使用v-show或v-if控…

react组件如何通讯

react组件如何通讯

React 组件通讯方式 React 组件间的通讯方式主要包括以下几种方法,适用于不同场景下的数据传递和状态管理需求。 父子组件通讯(Props 传递) 父组件通过 props 向子组件传递数据或回…

vue表格组件实现

vue表格组件实现

Vue表格组件实现 基础表格实现 使用el-table组件实现基础表格功能。安装Element UI后,引入el-table和el-table-column组件。 <template>…

react参数如何传递

react参数如何传递

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