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