学习React(24) - 介绍Refs的用法

// RefsDemo.js 文件
import React, { Component } from 'react'

class RefsDemo extends Component {
    constructor(props) {
        super(props)
        // 用到这个方法createRef() 
        this.inputRef = React.createRef()
        // call back ref
        this.cbRef = null
        this.setCbRef = (element) => {
            this.cbRef = element
        }
    }
    
    componentDidMount() {
        if(this.cbDef) {
            this.cbRef.focus()
        }

        // this.inputRef.current.focus()
        // console.log(this.inputRef)
    }

    clickHandler = () => {
        alert(this.inputRef.current.value)
    }

    render() {
        return (
            <div>
                <input type="text" ref={this.inputRef}/>
                <input type="text" ref={this.setCbRef}/>
                <button onClick={this.clickHandler}>Click</button>
            </div>
        )
    }
}

export default RefsDemo

在App.js 文件中

// App.js 文件
import React from 'react';
import './App.css';
import RefsDemo from './RefsDemo';

function App() {
  return (
    <div className="App">
      <RefsDemo/>
    </div>
  );
}

export default App;

结果如下:
在这里插入图片描述
在这里插入图片描述

当我在第一个方框里输入"world"时,点击Click按钮,就会弹出Alert框
在这里插入图片描述

如果觉得不错的话,就用点赞来代替五星好评吧!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章