react学习之props

react 三大属性值之一props,获取标签属性上的属性值,函数组件和class组件都有这个属性。

函数组件

  • 简单的使用
function Demo(props){
	return (
		// 获取标签上传入的name属性值
		<div>我是:{props.name}</div>
	)
}

ReactDOM.render(<Demo name="Tom" />, document.getElementById("app))
  • 限制传入属性值得类型和默认值
  • 15版本以前 PropTypes 在React核心库上,16版本以后,PropTypes 独立出一个依赖包
  • 需要引入prop-types这个依赖包
function Demo(props){
	return (
		// 获取标签上传入的name属性值
		<div>我是:{props.name}, 性别:{props.sex}, 年龄:{props.age}</div>
	)
}

Person.propTypes = {
	name: PropTypes.string.isRequired, // 限制name必传,且为字符串
	sex: PropTypes.string, // 限制sex为字符串
	age: PropTypes.number, // 限制age为数值
}
        
// 指定标签属性的默认值
Person.defaultProps = {
	sex: '男', // sex默认值为男
	age: 18 // age默认值为18
}

ReactDOM.render(<Demo name="Tom" />, document.getElementById("app))

class 组件

  • 简单使用

class Person extends React.Component {
	render(){
		// 获取标签上的属性值
		const {name, sex, age} = this.props;
		return (
			<ul>
				<li>姓名:{name}</li>
				<li>性别:{sex}</li>
				<li>年龄:{age}</li>
			</ul>
		)
	}
}
ReactDOM.render(<Person name="jerry" age={19} sex="男" />, document.getElementById("app"))
  • 对props 属性值进行限制
  • 使用static 限制定义在组件原型上
class Person extends React.Component {
	render(){
		// 获取标签上的属性值
		const {name, sex, age} = this.props;
		static propTypes = {
                name: PropTypes.string.isRequired, // 限制name必传,且为字符串
                sex: PropTypes.string, // 限制sex为字符串
                age: PropTypes.number, // 限制age为数值
                speak: PropTypes.func // 限制speak为函数
            }
		// 指定标签属性的默认值
        static defaultProps = {
                sex: '男', // sex默认值为男
                age: 18 // age默认值为18
            }
		return (
			<ul>
				<li>姓名:{name}</li>
				<li>性别:{sex}</li>
				<li>年龄:{age}</li>
			</ul>
		)
	}
}
ReactDOM.render(<Person name="jerry" age={19} sex="男" />, document.getElementById("app"))
  • class 的constructor(构造器)的参数会接收到props
class Demo extends React.Component{
	constructor(props) {
		// 先通过super将传入的值传到React.Component的constructor,在组件的constructor 就可以访问到this.props;
		super(props)
		}
}

总结:props 属性是接收组件标签上的属性值,以对象(key-value)的形式保存到props上。
要对props的属性进行类型限制和设置默认值,在15.x版本及以前直接使用React.propTypes.xxx,16.x版本及以后需要引入prop-types包(使用ts开发可以忽略)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值