props的基本使用和特点

本文深入讲解React中组件Props的使用,包括Props的作用、特点及如何在函数组件和类组件中接收和使用数据。同时,提供了代码示例,帮助读者理解Props在实际开发中的应用。

组件的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'))

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值