React-props

Posted CaoPengCheng&

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React-props相关的知识,希望对你有一定的参考价值。

React-props

【1】props

(1)props
	接收传递给组件的数据
	传递数据:给组件标签添加属性

(2)props传教接收
	传递数据:
		name="jack" age={19}表示传递数据
		<Hello name="jack" age={19} />
		
	接收数据:
	a,函数组件
const Hello = (props)=> {
	console.log(props)
		return(
			<div>接受数据:{props.name}</div>
		)
}
	b,类组件
class Hello extends React.Component{
	render(){
		return(
			return(
			<div>接受数据:{this.props.age}</div>
		)
	}
}
	【注:数值数据加{},非数值加""】

【2】props特点

(1)可以给任意组件传递任意类型
	a,传递数组:
	<Hello colors={['red','green','blue']} />

	b,传递函数:
	<Hello fn={() => console.log('函数')} />

	c,传递jsx
<Hello tag={<p>p标签</p>}} />

class Hello extends React.Component{
	render(){
		return(
			return(
			<div>
			接受数据:{this.props.age}
			//将p标签渲染
			{this.props.tag}
			</div>
		)
	}
}
(2)props是只读的对象,只能读取属性的值,无法修改
(3)使用类组件时,如果写了构造函数,应该将props传递给super(),
	否则无法在构造函数中获取到props
class Hello extends React.Component{
constructor(props){
		super(props)
	}

	render(){
		return(
			return(
			<div>
			接受数据:{this.props.age}
			//将p标签渲染
			{this.props.tag}
			</div>
		)
	}
}

【3】children属性

表示组件标签的子节点,当组件标签有子节点时,props就会有该属性
const Hello = () => {
return(
	<div>
		组件子节点
		{props.children}
	</div>
)
}

<Hello>我是子节点</Hello>
children属性与普通的props一样,值可以是任意值(文本,React元素,组件,函数)

【4】props校验

无法保证传入什么样的格式的数据
props校验:允许在创建组件时,就指定props的类型,格式等
捕获使用数组时因为props导致的错误,给出明确的错误提示

(1)安装prop-types
	npm i props-types
(2)导入prop-types包
(3)使用 组件名.propTypes = {}来给组件的props添加校验规则
import ProTypes from 'prop-types'

const App = (props) =>{
	return(
		<h1>Hi,{props.colors}</h1>
	)

}
App.propTypes = {
	colors:PropTypes.array
}
	约定colors属性为array类型
	如果类型不对,则报出明确错误,便于分析错误原因
(4)校验规则通过PropTypes对象指定

【5】props校验约束规则

(1)常见类型:array,bool,func,number,object,string
(2)React元素类型:element
(3)必填项:isRequired
	colors:PropTypes.array.isRequired
(4)特定结构:shape({
				xxx:PropTypes.xxx
				xxx:PropTypes.xxx
			})

【6】props默认值

组件没有传值,便使用默认值
const App = (props) => {
	console.log(props)
	return(
		<div>
			<h1>{props.pageSize}</h1>
		</div>
	)

}
App.defaultProps = {
	pageSize:10
}

以上是关于React-props的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段——CSS选择器

谷歌浏览器调试jsp 引入代码片段,如何调试代码片段中的js

片段和活动之间的核心区别是啥?哪些代码可以写成片段?

VSCode自定义代码片段——.vue文件的模板

VSCode自定义代码片段6——CSS选择器

VSCode自定义代码片段——声明函数