Props的基本使用
props传递接受数据
1.在组件标签上添加属性
2.类组件使用 this.props 接收数据。函数组件使用参数 props 接收数据。
- // 类接受 props 数据
- class App extends React.Component {
- render() {
- return (
- <div>
- <h1>姓名:{this.props.name}</h1>
- <h1>年龄:{this.props.age}</h1>
- </div>
- )
- }
- }
-
- ReactDOM.render(<App name="Tom" age="18" />, document.getElementById('root'))
- // 函数接收 props 数据
- const App = props => {
- return (
- <div>
- <h1>姓名:{props.name}</h1>
- <h1>年龄:{props.age}</h1>
- </div>
- )
- }
-
- ReactDOM.render(<App name="Tom" age="18" />, document.getElementById('root'))
props 特点
可以给组件传递任意类型的数据
props 传递的数据是只读的数据。只能读取属性的值,而不能进行修改。
在使用类组件时,若写了构造函数,必须将 props 传给 super()
- constructor(props) {
- super(props)
- ...
- }
Props深入
Children属性:
表示组件的子节点。有子节点的时候, Props 就会有这个属性
和普通的Props 一样,值可以是任意值
Props的校验:
对于组件来说 Props 是外来的,无法保证组件的使用者传入的数据格式
传入的数据格式不对的话,会导致组件内部报错,且不知道明确的错误原因
Props校验:在创建组件的时候,会指定 Props 的类型和格式---这样就算格式出错也会给出一个明确的错误。
使用步骤:
安装 Props-types(npm i prop-types/yarn add prop-types)
导入prop-types 包
使用 组件名.propType = {} 给组件添加校验规则
- ```javascript
- import propTypes from 'prop-types'
- function App(props) {
- return (
- <h1>{props.name}</h1>
- )
- }
- App.propTypes = {
- name : PropTypes.string
- }
- ```
约束规则
常见类型: Array、number、object、string、bool、func
React 元素类型: element
是否必填:isRequired
特定结构的对象: shape({ }) ----- 约束多个属性的时候,整合到这个对象中一起书写
Props的默认值
- const App = props => {
- return (
- <div>props.name/div>
- )
- }
- //添加默认值
- App.defaultProps = {
- name : 'Tom'
- }