React prop使用和传入限制、默认值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React prop使用和传入限制、默认值相关的知识,希望对你有一定的参考价值。
参考技术A 作用:接收传递给组件的数据
特点:
1、可以给组件传递任意类型的数据
2、props是只读的对象,只能读取属性的值,无法修改对象
3、注意:使用类组件时,如果写了构造函数,应该将props传递给super(),否则,无法在构造函数中获取到props
一定要引入 prop-types.js 否则会报错
1、限制规则使用Person.propTypes进行限制,有func(函数),string(字符串),number(数字类型),isRequired(不能为空)
2、设置默认值Person.defaultProps,进行props默认值的设置
React8 props的children校验默认值
【React】8 props的children、校验、默认值
1. props.children 属性
- children 属性:表示
组件标签的子节点。
当组件标签有子节点时,props就会有该属性。 - chidren 属性与普通的props一样,值可以是
任意值(文本、React元素、组件,甚至是函数)
demo:
import React from 'react'
import ReactDOM from 'react-dom/client'
//组件1
class User extends React.Component
render()
return (
// 传入非函数children
// <Node1>hello</Node1>
// <Node1><button>hello</button></Node1>
//传入函数children
<Node1>
() => console.log("函数1")
</Node1>
)
//组件
const Node1 = (props) =>
//使用函数children
props.children()
return (
//使用非函数children
// <div>node1--props.children</div>
<div>node1--</div>
)
const root = ReactDOM.createRoot(document.getElementById("root"))
root.render(<User />)
效果:
2. props 校验
使用步骡
- 安装包 prop-types ( yarn add prop-types /
npm i prop-types
) - 导入 prop-types包,
import PropTypes from 'prop-types'
; - 使用
组件名.propTypes =
来给组件的props添加校验规则 - 按验规见面过 PropTypes象来指定
import React from 'react'
import ReactDOM from 'react-dom/client'
//导入校验包
import PropTypes from 'prop-types'
//组件
const Node1 = (props) =>
console.log(props)
return (
<div>node1--props.colors[0]</div>
)
//添加校验规则
Node1.propTypes =
colors: PropTypes.array
const root = ReactDOM.createRoot(document.getElementById("root"))
// root.render(<Node1 colors=["red", "blue"] />)
root.render(<Node1 colors="qq" />)
效果:
传入错误参数时,会提示类型错误
常用验证规则:
若是必填则后面加.isRequired
MyComponent.propTypes =
// You can declare that a prop is a specific JS primitive. By default, these
// are all optional.
optionalArray: PropTypes.array,
optionalBool: PropTypes.bool,
optionalFunc: PropTypes.func,
optionalNumber: PropTypes.number,
optionalObject: PropTypes.object,
optionalString: PropTypes.string,
optionalSymbol: PropTypes.symbol,
// Anything that can be rendered: numbers, strings, elements or an array
// (or fragment) containing these types.
//验证是否为节点
optionalNode: PropTypes.node,
//验证是否为元素
// A React element (ie. <MyComponent />).
optionalElement: PropTypes.element,
//验证是否为元素类型
// A React element type (ie. MyComponent).
optionalElementType: PropTypes.elementType,
//验证是否为另一个类的实例
// You can also declare that a prop is an instance of a class. This uses
// JS's instanceof operator.
optionalMessage: PropTypes.instanceOf(Message),
//验证传入值是否在给定范围
// You can ensure that your prop is limited to specific values by treating
// it as an enum.
optionalEnum: PropTypes.oneOf(['News', 'Photos']),
//验证传入类型是否在给定范围
// An object that could be one of many types
optionalUnion: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.instanceOf(Message)
]),
// An array of a certain type
optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
// An object with property values of a certain type
optionalObjectOf: PropTypes.objectOf(PropTypes.number),
// You can chain any of the above with `isRequired` to make sure a warning
// is shown if the prop isn't provided.
// An object taking on a particular shape
optionalObjectWithShape: PropTypes.shape(
optionalProperty: PropTypes.string,
requiredProperty: PropTypes.number.isRequired
),
// An object with warnings on extra properties
optionalObjectWithStrictShape: PropTypes.exact(
optionalProperty: PropTypes.string,
requiredProperty: PropTypes.number.isRequired
),
requiredFunc: PropTypes.func.isRequired,
// A value of any data type
requiredAny: PropTypes.any.isRequired,
// You can also specify a custom validator. It should return an Error
// object if the validation fails. Don't `console.warn` or throw, as this
// won't work inside `oneOfType`.
//回调函数:自定义验证规则
customProp: function(props, propName, componentName)
if (!/matchme/.test(props[propName]))
return new Error(
'Invalid prop `' + propName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
,
// You can also supply a custom validator to `arrayOf` and `objectOf`.
// It should return an Error object if the validation fails. The validator
// will be called for each key in the array or object. The first two
// arguments of the validator are the array or object itself, and the
// current item's key.
customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName)
if (!/matchme/.test(propValue[key]))
return new Error(
'Invalid prop `' + propFullName + '` supplied to' +
' `' + componentName + '`. Validation failed.'
);
)
;
3. props默认值
指定 props 的默认值, 这个方法只有浏览器编译以后才会生效
class HandsomeBoy extends Component
// 设置默认值
//defaultProps 可以为 Class 组件添加默认 props,基于 static 的写法
static defaultProps =
name:'pyq'
constructor(props)
super(props)
render()
return <section>this.props.name</section>
指定 props 的默认值,这个方法会一直生效
class Age extends Component
render()
return <section>this.props.name</section>
// 默认值的第二种,指定 props 的默认值,这个方法会一直生效
Age.defaultProps =
name:18
以上是关于React prop使用和传入限制、默认值的主要内容,如果未能解决你的问题,请参考以下文章
8. react 基础 - props 默认值和类型限制 与 Props , State , render 函数 关系