当前位置:首页 > 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,避免逐一声明。

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 进行类型校验,确保数据符合预期。

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 可以直接在组件标签内传递内容(如文本、元素或其他组件)。

react 如何传递props

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

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

标签: reactprops
分享给朋友:

相关文章

react如何开发组件

react如何开发组件

React 组件开发基础 React 组件分为函数组件和类组件两种形式。函数组件是现代 React 开发的主流方式,结合 Hooks 可以实现完整功能。 函数组件示例: function Gree…

react 如何分页

react 如何分页

分页实现方法 在React中实现分页功能可以通过多种方式完成,具体取决于数据来源(如API或本地数据)和UI库的选择。以下是常见的实现方法: 使用本地数据分页 对于存储在组件状态或Context中…

react 如何启动

react 如何启动

创建 React 项目 使用官方工具 create-react-app 快速初始化项目,需提前安装 Node.js(版本 ≥ 14.0.0)和 npm/yarn: npx create-react-…

如何监控react性能

如何监控react性能

使用 React Profiler API React 16.5 及以上版本内置了 Profiler API,可直接测量组件渲染时间。通过 <React.Profiler> 包裹目标组件,…

vscode如何配置react

vscode如何配置react

配置 VSCode 进行 React 开发 安装必要插件 ES7+ React/Redux/React-Native snippets:提供 React 代码片段快速生成功能。 Prettier -…

小白如何搭建react

小白如何搭建react

安装 Node.js 和 npm 确保系统已安装 Node.js(包含 npm)。可通过官网下载安装包(https://nodejs.org/),选择 LTS 版本。安装完成后,终端运行以下命令验证版…