react中的ref三种形式

1,字符串形式

  <!-- 创建盒子 -->
  <div id="test">

  </div>   


 <script type="text/babel">
      class Demo extends React.Component{
        render(){
          return(
            <div>
              <input type="text" ref='input1' />
              <button onClick={this.showDate}>点我提示左侧的数据</button>
              <input type="text" onBlur={this.shhowDate1} ref='input2'/>
            </div>
          )
        }
        showDate = () =>{
          console.log(this.refs.input1.value,'input1')
        }
        shhowDate1 = () =>{
          console.log(this.refs.input2.value,'input1')
        }
      }
      ReactDOM.render(<Demo />,document.getElementById('test'))
    </script>

2,回调形式

          /**
           * 1,在标签上使用回调形式
           * <input type="text" ref={c =>this.input1 = c }/>
           * 2,使用获取
           * this.input1
           * **/
  <!-- 创建盒子 -->
  <div id="test">

  </div>

 <script type="text/babel">
      class Test extends React.Component {
        render(){
          return (
            <div>
              <input type="text" ref={c =>this.input1 = c }/>
              <button onClick={this.showDate}>点我</button>
              <input type="text" ref={c =>this.input2 = c}/>
            </div>
          )
        }
        showDate = () =>{
          console.log(this.input1.value)
          console.log(this.input2.value)
        }
      }
      ReactDOM.render(<Test />,document.getElementById('test'))
    </script>

3,createRef形式

        /**
         *  1,引用语法
         * aaa =  React.createRef()
         * 2,定义在标签上
         * <input type="text" ref={this.aaa}/>
         * 3,使用获取
         * console.log(this.aaa.current.value,'this.mydata')
         * **/
    <script type="text/babel">
      class MyComponent extends React.Component{
        /**
         *  1,引用语法
         * React.
         * **/
        mydata = React.createRef()
        mydata1 = React.createRef()
        render(){
          return (
            <div>
              <input type="text" ref={this.mydata}/>
              <button onClick={this.clickDate} >点击</button>
              <input type="text" ref={this.mydata1} onBlur={this.clickDate1}/>
            </div>
          )
        }
        clickDate = () =>{
          console.log(this.mydata.current.value,'this.mydata')
        }
        clickDate1 = () =>{
          console.log(this.mydata1.current.value,'this.mydata1')
        }
      }
      ReactDOM.render(<MyComponent/>,document.getElementById('test'))
    </script>

上一篇:Gradle使用腾讯镜像提高下载速度


下一篇:提示词工程 (Prompt Engineering) 最佳实践