当前位置:首页 > React

react 如何传递props

2026-03-30 21:21:16React

传递 Props 的基本方式

在 React 中,父组件可以通过属性(props)将数据传递给子组件。子组件通过函数参数或 this.props(类组件)接收这些数据。

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

// 子组件(函数组件)
function ChildComponent(props) {
  return <div>{props.greeting}</div>;
}

// 子组件(类组件)
class ChildComponent extends React.Component {
  render() {
    return <div>{this.props.greeting}</div>;
  }
}

传递多个 Props

可以通过展开运算符一次性传递多个 props,避免逐一声明。

react 如何传递props

function ParentComponent() {
  const user = { name: "Alice", age: 25 };
  return <ChildComponent {...user} />;
}

默认 Props

为组件设置默认 props,防止未传递时出现未定义错误。

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

ChildComponent.defaultProps = {
  greeting: "Default greeting"
};

Props 类型校验

使用 PropTypes 或 TypeScript 对 props 进行类型校验,确保数据符合预期。

react 如何传递props

import PropTypes from 'prop-types';

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

ChildComponent.propTypes = {
  greeting: PropTypes.string.isRequired
};

传递函数作为 Props

可以将函数作为 props 传递给子组件,实现父子组件通信。

function ParentComponent() {
  const handleClick = () => alert("Button clicked");
  return <ChildComponent onClick={handleClick} />;
}

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

通过 Children Prop 传递内容

通过 children prop 可以直接在组件标签内传递内容(如文本、元素或其他组件)。

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

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

标签: reactprops
分享给朋友:

相关文章

如何改造react

如何改造react

改造 React 项目的关键方法 分析当前项目结构 通过评估现有组件、状态管理和依赖项,明确需要改进的部分。使用工具如 webpack-bundle-analyzer 识别性能瓶颈。 升级 Reac…

react如何收录

react如何收录

React 收录方法 React 的收录主要涉及搜索引擎优化(SEO)和预渲染技术。由于 React 是单页应用(SPA),默认情况下内容由 JavaScript 动态生成,可能导致搜索引擎爬虫难以收…

react如何调试

react如何调试

调试 React 应用的方法 使用 React Developer Tools React Developer Tools 是 Chrome 和 Firefox 的浏览器扩展,可以检查组件树、状态和…

react架构如何

react架构如何

React 架构核心概念 React 的架构围绕组件化、虚拟 DOM 和单向数据流设计。组件是构建用户界面的独立模块,分为函数组件和类组件。虚拟 DOM 通过高效的 Diff 算法减少直接操作真实 D…

react如何卸载

react如何卸载

卸载 React 项目或依赖 如果需要完全卸载 React 项目或相关依赖,可以按照以下步骤操作: 删除项目文件夹 直接删除整个项目文件夹是最彻底的方式。确保已备份重要代码或配置文件。 卸载全局安…

如何启动react

如何启动react

安装Node.js 确保系统已安装Node.js(建议使用LTS版本),可通过官网下载并安装。安装完成后,在终端运行以下命令验证版本: node -v npm -v 创建React项目 使用官方工具…