【React】入门第五天 - state和refs

在这里插入图片描述

state

什么是state

state是状态

stateprops的区别

props是组件对外部的接口,如果子组件需要使用父组件的数据就可以通过props来进行数据传递,

state是组件对内的接口,组件自身可能有需要管理的数据,对管理数据的属性就是state

如果需要使用state 不能使用无状态组件

class MyComponent extends React.Component {
    
    
  constructor(props) {
    
    
      super(props)
    // state是可变的,props 是只读的
      this.state = {
    
    
          name : "react"
      }
  }

  // this.setState({key:value}) 是异步的,react 就会自动触发render进行数据的渲染
  render(){
    
    
      return ( <div>我是组件
              <button onClick= {
    
    ()=>{
    
    this.setState({
    
    name:"vue"})}}>changeValue</button>
              <div></div>
              name :{
    
    this.state.name}
          </div> )
  }
} 

refs

refs: react当中提供了一个refs的数据 不能再无状态组件当中进行使用 因为无状态组件没有实例

表示当前组件的真正实例的引用 他会返回当前属性的元素

标识组件内部的元素

官方建议不要过度使用refs需要优先考虑state

refs三种方式使用

  1. 字符串
class MyComponent extends React.Component {
    
    

    fun = ()=>{
    
    
        console.log(this.refs.demoInput.value)
    }

    render (){
    
    
        return ( <div>
            我是一个组件
                <input type="text" ref="demoInput " placeholder = "请输入"/>
                <button onClick = {
    
    this.fun} >click me to get value</button>
            </div> ) 
    }
} 
  1. ref回调函数就是在dom节点上或者组件上挂载函数 函数的入参是dom 节点
class MyComponentB extends React.Component {
    
    
    fun = ()=>{
    
    
        console.log(this.inputValue.value)
    }

    render (){
    
    
        return ( <div>
            我是一个组件 回调
                <input type="text" ref={
    
    (input)=>{
    
    this.inputValue = input}} placeholder = "请输入"/>
                <button onClick = {
    
    this.fun} >click me to get value</button>
            </div> ) 
    }
} 
  1. React.createRef() (react 16.3新提供的方式)
// 把值付给一个变量,使用ref的current属性拿到这个节点
class MyComponentC extends React.Component {
    
    
    constructor(props){
    
    
        super(props)
        this.myRef =React.createRef()
    }

    fun = ()=>{
    
    
        console.log(this.myRef.current.value)
    }

    render (){
    
    
        return ( <div>
            我是一个组件 回调
                <input type="text" ref={
    
     myRef } placeholder = "请输入"/>
                <button onClick = {
    
    this.fun} >click me to get value</button>
            </div> ) 
    }
} 

猜你喜欢

转载自blog.csdn.net/weixin_42126468/article/details/104799112