React组件三大属性之props

一、理解

1、每个组件对象都会有 props(properties 的简写)属性
2、每组标签的所有属性都保存在 props

二、作用

1、通过标签属性从组件向外组件内传递变化的数据
2、注意:组件内部不要修改 props 数据

简化后代码:

//创建组件
class Person extends React.Component{
//constructor构造器可写可不写
	constructor(props){
		//构造器是否接收props,是否传递给super,取决于:是否希望在构造器中通过this访问props
		// console.log(props);
		super(props)
		console.log('constructor',this.props);
	}

	//对标签属性进行类型、必要性的限制
	static propTypes = {
		name:PropTypes.string.isRequired, //限制name必传,且为字符串
		sex:PropTypes.string,//限制sex为字符串
		age:PropTypes.number,//限制age为数值
	}

	//指定默认标签属性值
	static defaultProps = {
		sex:'男',//sex默认值为男
		age:18 //age默认值为18
	}
	
	render(){
		// console.log(this);
		const {name,age,sex} = this.props
		//props是只读的
		//this.props.name = 'jack' //此行代码会报错,因为props是只读的
		return (
			<ul>
				<li>姓名:{name}</li>
				<li>性别:{sex}</li>
				<li>年龄:{age+1}</li>
			</ul>
		)
	}
}

//渲染组件到页面
ReactDOM.render(<Person name="jerry"/>,document.getElementById('test1'))

三、props的children用法

如下例,一个 span 标签在 Parent 中作为Child的子节点传入,可在 Child 中通过 this.props.children 取到:

class Parent extends React.Component {
  render() {
    return (
    <Child>
        <span>{'child node'}</span>
      </Child>
    );
  }
}
class Child extends React.Component {
  render() {
    return (
      <div>
        {this.props.children} //child node
      </div>
    );
  }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值