组件的props( props是一个对象 )
作用:接收传递给组件的数据
特点:1、可以给组件传递任意类型的数据
2、props是只读的对象,只能读取属性的值,无法修改对象
3、注意:使用类组件时,如果写了构造函数,应该将props传递给super(),否则,无法在构造函数中获取到props!!!
代码如下:
class One extends React.Component {
constructor(props) {
super(props)
console.log(this.props)
}
render() {
console.log(this.props)
return (
<div>
<h1>接收的数据: {this.props.name}</h1>
{this.props.tag}
{this.props.fn()}
</div>
)
}
}

传递数据:给组件标签添加属性
接收数据:函数组件通过参数props接收数据,类组件通过this.props接收数据
函数组件
function One(props) {
return (
<div>
<h1>接收的数据: {props.name}</h1>
</div>
)
}
类组件
class One extends React.Component {
render() {
console.log(this.props)
return (
<div>
<h1>接收的数据: {this.props.name}</h1>
{this.props.tag}
{this.props.fn()}
</div>
)
}
}
ReactDOM.render(<One name= "lannie" age={18} tag={<p>这是一个p标签</p>} color={["red","yellow","blue"]} fn={()=>{console.log('这是一个函数')}}/>, document.getElementById('root'))
本文深入讲解React中组件Props的使用,包括Props的作用、特点及如何在函数组件和类组件中接收和使用数据。同时,提供了代码示例,帮助读者理解Props在实际开发中的应用。
917

被折叠的 条评论
为什么被折叠?



