一、理解
1、每个组件对象都会有 props
(properties 的简写)属性
2、每组标签的所有属性都保存在 props
中
二、作用
1、通过标签属性从组件向外组件内传递变化的数据
2、注意:组件内部不要修改 props
数据
简化后代码:
html" title=javascript>javascript">//创建组件
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 取到:
js">class Parent extends React.Component {
render() {
return (
<Child>
<span>{'child node'}</span>
</Child>
);
}
}
js">class Child extends React.Component {
render() {
return (
<div>
{this.props.children} //child node
</div>
);
}
}