ref有什么用:按照我自己的理解就是:给元素打标记,然后更方便的拿到DOM节点
首先看一个案例:点击button把input中输入的值弹出
class App extends React.Component {
showDate = ()=> {
let input = document.getElementById('input1')
alert(input.value)
}
render(){
return (
<div>
<input placeholder= '请输入内容' id='input1' />
<button onClick= {this.showDate}>点击我弹出input的内容</button>
</div>
)
}
}
const rootElement = document.getElementById("app")
ReactDOM.render(<App/>, rootElement);
有没有发现在showDate中我们用的是原生js来获取的标签,代码特别长,而使用下面几种react封装的方法会简单一些
- 字符串形式的ref
- 回调函数形式的ref
- createRef() API
下面我们分别用上面三种形式来重写以下上面的案例
字符串形式的ref
class App extends React.Component {
showDate = ()=> {
let {input1} = this.refs // === {let input1 = this.refs.input1}
alert(input1.value)
}
render(){
return (
<div>
<input placeholder= '请输入内容' ref='input1' />
<button onClick= {this.showDate}>点击我弹出input的内容</button>
</div>
)
}
}
const rootElement = document.getElementById("app")
ReactDOM.render(<App/>, rootElement);
ref
就像id一样,给标签进行标记,let {input1} = this.refs
通过这个标记,拿到真实的DOM节点, 然后进行操作。但是,在官网中,有下面图中的这段话:
image.png
react不建议我们使用它,因为存在一些问题,有可能在未来的版本中被移除
回调函数形式的ref
回调函数形式的ref有两种写法
class App extends React.Component {
showDate = ()=> {
let {input1} = this.input1
alert(input1.value)
}
render(){
return (
<div>
<input placeholder= '请输入内容' ref={(c)=> {this.input1 = c}} />
<button onClick= {this.showDate}>点击我弹出input的内容</button>
</div>
)
}
}
const rootElement = document.getElementById("app")
ReactDOM.render(<App/>, rootElement);
class App extends React.Component {
showDate = ()=> {
alert(this.input1.value)
}
saveInput1=(c)=> {
this.input1 = c
console.log('1');
}
render(){
return (
<div>
<input placeholder= '请输入内容' ref={this.saveInput1} />
<button onClick= {this.showDate}>点击我弹出input的内容</button>
</div>
)
}
}
const rootElement = document.getElementById("app")
ReactDOM.render(<App/>, rootElement);
两种有什么区别呢?看官网中的解释
image.png
第一种ref回调函数会以内联函数的形式定义的,在更新的时候他会执行两次,第一次传入参数null,第二次传入参数DOM元素,
第二种ref回调函数以class的绑定函数的形式定义的,可以避免上面那种情况,
但是在大多数情况下是无关紧要的,所以使用上面哪种方式都行
createRef() API
class App extends React.Component {
myRef = React.createRef() myRef = React.createRef() 这个函数
showDate = ()=> {
alert(this.myRef.current.value) 拿到元素用this.myRef.current
}
render(){
return (
<div>
<input placeholder= '请输入内容' ref={this.myRef} /> 定义ref={this.myRef}
<button onClick= {this.showDate}>点击我弹出input的内容</button>
</div>
)
}
}
const rootElement = document.getElementById("app")
ReactDOM.render(<App/>, rootElement);
以上就是ref的三种使用方法