React 中的 Props

发布于:2025-04-02 ⋅ 阅读:(22) ⋅ 点赞:(0)

Props(Properties 的缩写)是 React 中用于组件间通信的核心机制。它们允许数据从父组件单向传递到子组件。Props 是 React 组件不可变(只读)的输入参数,这种特性使得组件更加可预测且易于维护。

Props 的核心特性

单向数据流:Props 只能从父组件传递到子组件,不能反向传递

只读性:接收组件不能修改传入的 props

动态性:Props 使组件能够根据传入数据呈现不同内容

类型安全:结合 PropTypes 或 TypeScript 可以确保 props 类型正确

在 React 中使用 Props 的方法

1. 将 Props 传递给功能组件 功能组件通过参数接收 props

对象:

function Welcome(props) {   return <h1>Hello, {props.name}</h1>; } // 使用组件 <Welcome name="Alice" />

2. 在功能组件中使用解构 解构赋值使代码更简洁:

function Welcome({ name }) {   return <h1>Hello, {name}</h1>; } // 使用组件 <Welcome name="Bob" />

3. 传递多个 props 可以同时传递多个属性:

function UserProfile({ name, age, location }) {   return (     <div>       <h2>{name}</h2>       <p>Age: {age}</p>       <p>Location: {location}</p>     </div>   ); } // 使用组件 <UserProfile name="Charlie" age={28} location="New York" />

4. 设置默认 Props 为 props 提供默认值:

function Greeting({ name = 'Guest' }) {   return <p>Welcome, {name}!</p>; }

5. 将 Props 传递给类组件 类组件通过 this.props 访问 props:

class Welcome extends React.Component {   render() {     return <h1>Hello, {this.props.name}</h1>;   } } // 使用组件 <Welcome name="David" />

6. 传递子元素 (children) 通过 props.children 传递组件内容:

function Card({ children }) {   return <div className="card">{children}</div>; } // 使用组件 <Card>   <h3>Title</h3>   <p>Content goes here</p> </Card>

Props 验证 使用 PropTypes 或 TypeScript 验证 props 类型:

import PropTypes from 'prop-types'; function User({ name, age }) {   // 组件实现 } User.propTypes = {   name: PropTypes.string.isRequired,   age: PropTypes.number }; User.defaultProps = {   age: 18 };