react学习6-React 组件接收数据props和类组件状态state

组件接收数据props

  • 必须继承React.Component才可以成为一个类组件
  • render方法的作用:产生组件的模板,属于react的核心api,名称固定
  • 必须通过this.props获取父组件传递数据,是只读的,不可以修改。
class Nihao extends React.Component {
    render () {
        console.log(this.props)
        let uname = this.props.uname
        return (
            <div>
                类组件: {uname}
            </div>
        )
    }
}

类组件状态state

状态是组件私有的,并且完全被组件控制(只有类组件有状态,函数组件没有状态)。

类组件的数据来源有两个:

  • 内部的状态state
    • state可以修改
    • 不要直接修改 State,使用 this.setState() 来更新类组件 state。
    • 构造函数是唯一可以给 this.state 赋值的地方。
  • 父组件传递的props
    • 是只读的,不可以修改
class StateTest extends React.Component {
     constructor (props) {
       // 类组件第一行需要添加super并且传递props参数
       super(props)
       this.state = {
         info: 'nihao'
       }
     }

    // 类组件的内部状态需要使用state名称
    // 类组件状态的简化写法
    state = {
        info: 'hello'
    }

render () {
    const { info } = this.state
    const { msg } = this.props
    return (
        <div>
            <h1>有状态的组件:{info}</h1>
            <h1>有状态的组件:{msg}</h1>
        </div>
    )
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值