1

React之ref

  React中关于Ref实际上就是为dom元素提供一个双向绑定,但是对于官方来说  能少用就少用  但是我偏不  因为我刚学  我要用熟练  我要高薪

  ref的实现有三种方法(字符串方式【贼简单】,回调函数【稍微复杂点】,createRef【最复杂但是最新】)

  今天我要用ref来操作dom使dom中的字体颜色发生改变

 

1     class MyCom extends React.Compinent{
2         consturctor (props){
3             super(props)
4             this.state={
5                bool:true  
6             }  
7         }    
8     }

1、字符串方法

1 render(){
2 return(
3 <div>
4/*直接在dom中*/5 <h1 ref="demoa">字符串方式使用ref</h1>
6 <button onClick={this.fun}>点击我修改字符串颜色样式</button>
7 </div>
8 )
9 }
1 fun=()=>{
2                 this.refs.demoa.style.color="red"
3    }

2、回调函数使用ref

<h1 ref={(aaa)=>{this.demo=aaa}}>回调函数使用ref</h1>
<button onClick(this.fun)>点我改变回调函数使用ref颜色</button>
fun(){

  this.demo.style.color="yellow"  

}

3、createRef使用ref

1、创建createRef

  this.democ = React.createRef()
//绑定
<h1 ref={this.democ}>createRef使用ref</h1> <button onClick={this.func}>点我修改createRef的样式</button>

 

 1 func=()=>{
 2    // 3使用
 3    console.log(this.democ)
 4    this.setState({
 5     bool:!this.state.bool
 6     },()=>{
 7     console.log(this.state.bool)
 8      this.state.bool? this.democ.current.style.color='gray':this.democ.current.style.color='red'
 9      })
10       }

 

比较三者异同:

1、从代码的简易程度来说createdRef的代码量是最多的,它需要创建一个this.xx=React.createRef()

通过字符串的方式来写ref来说是最少的

2、

 

posted @ 2021-01-21 20:15  small_zhouzhou  阅读(145)  评论(0)    收藏  举报
TOP