React 的 Props 是组件接收外部数据的手段,它们可以是任何有效的 JavaScript 值,比如字符串、数字、布尔值、函数、对象等。Props 使得组件可以重用,并且可以在不同的地方渲染不同的内容。

Props 的类型

  • 基本类型: 数字、字符串、布尔值等。
  • 对象和数组: 用于传递更复杂的数据结构。
  • 函数: 可以用来定义组件的行为。

使用 Props

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

// 使用 Props
<Welcome name="Alice" />

Prop 验证

React 提供了一个库 prop-types,可以用来验证组件传入的 Props 是否正确。

import PropTypes from 'prop-types';

class Greeting extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

Greeting.propTypes = {
  name: PropTypes.string.isRequired
};

注意事项

  • 不要在 render 方法中使用 Props: 这可能导致不必要的渲染。
  • 避免在 Props 中使用函数: 这可能导致组件行为难以预测。

更多关于 React Props 的信息

React Props 图解