React三大属性之Refs

342 阅读1分钟

refs是React中用来取得某个JSX组件或者某个DOM中的一些状态值的时候,用来获取节点的方法。在React官方的解释中,它的适用范围如下:

  • 管理焦点,文本选择或媒体播放。
  • 触发强制动画。
  • 集成第三方 DOM 库。 React文档中再三强调,请不要过度使用refs,所以当我们可以用dom原生对象解决时,尽量不要使用refs 依照之前的写法,首先是给出类组件和函数组件中refs的写法

类组件

在类中,refs有三种方式,目前最常用的是回调的形式使用,分别进行演示

//直接定义refs,已废弃
class App extends React.PureComponent{
    changeInput = ()=>{
        const {input} = this.refs
    }
    render() {
        return (
            <div>
                <input type="text" placeholder={"please input your value"} onBlur={this.changeInput} ref={"input"}/>
            </div>
        )
    }
}

//用回调的形式使用
class App extends React.PureComponent{
    changeInput = ()=>{
        console.log(this.inputRef);
    }
    render() {
        return (
            <div>
                <input type="text" placeholder={"please input your value"} onBlur={this.changeInput} ref={(el)=>{this.inputRef = el}}/>
            </div>
        )
    }
}

//用createRef
class App extends React.PureComponent{
    inputRef = React.createRef()
    changeInput = ()=>{
        console.log(this.inputRef.current);
    }
    render() {
        return (
            <div>
                <input type="text" placeholder={"please input your value"} onBlur={this.changeInput} ref={this.inputRef}/>
            </div>
        )
    }
}

以上就是类组件的三种Ref的写法

函数组件

function App(){
    const inputRef = useRef("")
    return (
        <div>
            <input type="text" placeholder={"please input your value"} ref={inputRef}/>
        </div>
    )
}

用一个useRef直接就完成了代码

面试常问:React中的refs作用是什么?

Refs 是 React 提供给我们的安全访问 DOM 元素或者某个组件实例的句柄。在类组件中,React将ref属性中第一个参数作为DOM中的句柄。而函数组件中,react用hooks的api useRef也能获得ref(在hooks中也常常用useRef的特性即不随着组件刷新而刷新存储的数据从而写一些不变的量)