React中的props是”properties”的意思。
官方文档定义:“ When React sees an element representing a user-defined component, it passes JSX attributes to this component as a single object. We call this object “props”.” 。
意思是:当React发现了用户自定义的组件,它会把JSX属性当做一个对象传递给这个组件,传递的这个对象就叫做props。
我们按照定义来举个例子: 现在在父组件Parent里面发现了一个用户自定义的组件Child,它的JSX属性为name=“Huan”,React会把这个属性当做一个对象传递给Child组件,这个对象就是props,也就是对象{name: “Huan”}:
class Parent extends React.Component {
render() {
return (
<div>
<h1>这里是Parent组件</h1>;
<Child name="Huan"/>
</div>
)
}
}
子组件Child收到父组件传递过来的props:{name: “Huan”}
,在Child组件中,这个props对象中的数据就可以使用了,此处使用 this.props.name
,显示内容为Huan。这样就完成了父子组件之间的通讯。
class Child extends React.Component {
render() {
return <p>Hello, {this.props.name}</p>
}
}
基本上就是这样使用props,有几点注意的地方:
参考文章为React官网文档,点此查看官网。
- END -