1. 字符串形式的ref
import React, { Component } from 'react'
export default class index extends Component {
showData = () => {
// 获取input节点
const { inputRef } = this.refs
// 输出input值
console.log(inputRef.value);
}
render() {
return (
<div>
<input ref="inputRef" type="text" placeholder="点击按钮提示数据"/>
<button onClick={ this.showData }>点我提示输入框值</button>
</div>
)
}
}
2. create形式的ref
import React, { Component } from 'react'
export default class index extends Component {
// React.createRef调用后返回一个容器,存储被ref标识的节点,单一使用。也就是说,没定义一个ref就要调用一次React.createRef
inputRef = React.createRef()
showData = () => {
const refVal = this.inputRef.current
console.log(refVal.value);
}
render() {
return (
<div>
<input ref={ this.inputRef } type="text" placeholder="点击按钮提示数据"/>
<button onClick={ this.showData }>点我提示输入框值</button>
</div>
)
}
}
3. 回调函数形式的ref
import React, { Component } from 'react'
export default class index extends Component {
showData = () => {
const { inputRef } = this
console.log(inputRef.value);
}
render() {
return (
<div>
{/* 这里传入一个回调函数 */}
<input ref={ currentNode => this.inputRef = currentNode } type="text" placeholder="点击按钮提示数据"/>
<button onClick={ this.showData }>点我提示输入框值</button>
</div>
)
}
}
总结:
- 综合以上三种形式各有优缺点,方式1与方式2写起来比较方便但是比较繁琐,方式三通过传入一个回调函数,不但简化了操作还不失优雅,显得代码逼格高些,但在最新版及以后的版本中,React官方使用函数式编程,所以更推荐使用
create
形式的ref。