大家好,欢迎来到 React Props 课程。在这一课中,我们将学习如何在 React 中使用 Props。
什么是 Props?
Props 是组件的属性,它可以用来在组件之间传递数据。Props 是只读的,这意味着子组件不能修改父组件传递的 Props。
如何使用 Props?
要使用 Props,需要在组件的 render() 方法中使用 this.props 对象。例如,以下代码演示了如何使用 Props:
javascript
class MyComponent extends React.Component {
render() {
return (
<div>
<h1>{this.props.title}</h1>
</div>
);
}
}
在上面的代码中,MyComponent 组件的 render() 方法使用 this.props.title 来获取父组件传递的 title Props。
默认 Props
如果父组件没有传递 Props,可以使用默认 Props 来指定 Props 的默认值。例如,以下代码演示了如何指定默认 Props:
javascript
class MyComponent extends React.Component {
static defaultProps = {
title: '默认标题'
};
render() {
return (
<div>
<h1>{this.props.title}</h1>
</div>
);
}
}
在上面的代码中,MyComponent 组件的 defaultProps 属性指定了 title Props 的默认值为"默认标题"。
Props 验证
React 提供了 Props 验证功能,可以用来确保父组件传递的 Props 是有效的。例如,以下代码演示了如何使用 Props 验证:
javascript
import PropTypes from 'prop-types';
class MyComponent extends React.Component {
static propTypes = {
title: PropTypes.string,
age: PropTypes.number
};
render() {
return (
<div>
<h1>{this.props.title}</h1>
<p>年龄:{this.props.age}</p>
</div>
);
}
}
在上面的代码中,MyComponent 组件的 propTypes 属性指定了 title Props 必须是字符串类型,age Props 必须是数字类型。
总结
Props 是组件的属性,它可以用来在组件之间传递数据。Props 是只读的,这意味着子组件不能修改父组件传递的 Props。可以使用默认 Props 来指定 Props 的默认值。React 提供了 Props 验证功能,可以用来确保父组件传递的 Props 是有效的。