React组件的三大属性 state props refs

React组件的三大属性 state props refs

state(最重要的属性)

  • state是组件对象最重要的属性,其值是对象,即可以包含多个数据

  • 组件相当于一个“状态机”,可以通过更新组件的state来更新对应的页面的显示(重新进行组件渲染)

  • 使用

    //初始化
    constructor(props){
        super(props)
        this.state = { //this是一个组件对象
            stateProp1: value1,
            stateProp2: value2
        }
    }
    //  读取第一个个状态值
    
    this.state.stateProp1
    //  更新状态,组件界面更新
    
    this.setState({
        stateProp1: value1,
        stateProp2: value2
    })
    
    

    props 属性

    每个组件对象都会有props(properties的简写)属性,组件标签的所有属性都保存在props中,所有组件标签的属性的集合对象

    作用:通过标签属性从组件外向组件内传递变化的数据 ,注意: 组件内部不要修改props数据

    ​ 父子传值

    使用:

  1. // 1.定义组件
      function Person(props) {
        return (
          <ul>
            <li>姓名:{props.name}</li>
            <li>年龄:{props.age}</li>
            <li>性别:{props.sex}</li>
          </ul>
        )
      }
     
      // 2.渲染组件标签
      const p1 = {
        name: 'lina',
        age: 18,
        sex: '女'
      }
      ReactDOM.render(<Person name={p1.name} age={p1.age} sex={p1.sex}/>, document.getElementById('person'))
    
    

    refs 属性

    ref用于标识组件内部某个元素

    refs 是标识集合

    使用:

    //1、先定义组件
            class InputComp extends React.Component {
                constructor(props) {
                    super(props)
                    //先对自定义函数进行bind操作
                    this.showInput = this.showInput.bind(this);
                    this.handleBlur = this.handleBlur.bind(this);
    
                }
                showInput(event) {
                    console.log(this);
                    alert(this.inputVal.value);
                }
                handleBlur(event) {//利用所有的事件均有一个event属性
                    alert(event.target.value);
                }
                render() {
                    return(
                        //this.inputVal=input 将当前input绑定到组件对象上。input代表               //当前这个input元素
                        <div>
                            <input type="text" ref={input => this.inputVal=input}/>
                            <button onClick={this.showInput}>点击获取值</button>
                            <input type="text" placeholder="失去焦点提示内容" onBlur={this.handleBlur}/>
                        </div>
                    )
                }
            }
            //2、渲染组件标签
            ReactDOM.render(<InputComp />,document.getElementById('text1'));
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值