携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第13天,点击查看活动详情
前言
组件是独立且封闭的单元,默认情况下,只能使用组件自己的数据。在组件化过程中,我们将一个完整的功能拆分成多个组件,以更好的完成整个应用的功能。而在这个过程中,多个组件之间不可避免的要共享某些数据。为了实现这些功能,就需要打破组件的独立封闭性,让其与外界沟通。这样的过程俗称组件通讯,而接收数据就需要 props。
组件的 props
- 组件是封闭的,要接收外部数据应该通过 props 来实现
- props 的作用:接收传递给组件的数据
- 传递数据:给组件标签添加属性
- 接收数据:函数组件通过参数 props 接收数据,类组件通过 this.props 接收数据
函数组件的 props
// 2.接受数据(函数组件通过参数 props 接收数据)
const Hello = (props) =>{
console.log(props)
return (
<div>
<h1>props:{props.name}</h1>
</div>
)
}
// 1.传递数据(给组件标签添加name和age属性)
ReactDOM.render(<Hello name="jack" age={19}/>, document.getElementById('root'))
类组件的 props
// 2.接受数据(类组件通过参数 this.props 接收数据)
class Hello extends React.Component {
render() {
return (
<div>
<h1>props:{this.props.age}</h1>
</div>
)
}
}
// 1.传递数据(给组件标签添加name和age属性)
ReactDOM.render(<Hello name="jack" age={19} />, document.getElementById('root'))
props 的特点
1)可以给组件传递任意类型的数据(字符串、值类、数组、函数、JSX表达式)
// 2.接受数据(类组件通过参数 this.props 接收数据)
class Hello extends React.Component {
render() {
console.log(this.props)
this.props.fn()
return (
<div>
<h1>props:{this.props.age}</h1>
{this.props.tag}
</div>
)
}
}
// 1.传递数据(给组件标签添加name和age属性)
ReactDOM.render(
<Hello
name="jack"
age={19}
colors={['black', 'red', 'blue']}
fn={() => { console.log('这是一个函数') }}
tag={<p>这是一个p标签</p>}
/>,
document.getElementById('root')
)
2)props 是只读的对象,只能读取属性的值,无法修改对象
3)注意:使用类组件时,如果写了构造函数,应该将 props 传递给 super(),否则,无法在构造函数中获取到 props
class Hello extends React.Component {
// eslint-disable-next-line no-useless-constructor
constructor(props) {
super(props)
console.log(props)
}
render() {
console.log(this.props)
this.props.fn()
return (
<div>
<h1>props:{this.props.age}</h1>
{this.props.tag}
</div>
)
}
}