1、字符串形式的ref不推荐使用(效率不高)
class GetInputValue extends React.Component {
getInput1Vaule=()=>{
console.log(this) /*this是实例本身,有refs属性*/
console.log(this.refs.input1.value)/*通过ref获取的是真是DOM*/
}
getInput2Value=()=>{
console.log(this.refs.input2.value)
}
render() {
return (
<div>
<input ref="input1"></input>
<button onClick={this.getInput1Vaule}>获取第一个input值</button>
<input ref="input2" onBlur={this.getInput2Value}></input>
</div>
)
}
}
ReactDOM.render(<GetInputValue />, document.getElementById('test'))
2、回调形式的ref(放在实例自身上,内联函数绑定ref在更新的时候会渲染两次,但是影响忽略不计)
class GetInputValue extends React.Component {
getInput1Vaule = () => {
console.log(this) /*this是实例本身,有refs属性*/
console.log(this.input1.value)/*通过ref获取的是真是DOM*/
}
getInput2Value = () => {
console.log(this.input2.value)
}
render() {
const { name, age, sex } = this.props /*接收传递过来的参数*/
return (
<div>
<input ref={currentNode => { console.log(currentNode, this,'currentNode'); this.input1 = currentNode }}></input>
<button onClick={this.getInput1Vaule}>获取第一个input值</button>
<input ref={currentNode => this.input2 = currentNode} onBlur={this.getInput2Value}></input>
</div>
)
}
}
ReactDOM.render(<GetInputValue />, document.getElementById('test'))
3、通过createRef进行绑定(官方最推荐)
class GetInputValue extends React.Component {
input1 = React.createRef() /*每绑定一个都要重新定义一个箭头函数挂载到实例上,要不后面定义的会覆盖前面的*/
input2 = React.createRef()
getInput1Vaule=()=>{
console.log(this.input1.current.value)
}
render() {
const { name, age, sex } = this.props /*接收传递过来的参数*/
return (
<div>
<input ref={this.input1}></input>
<button onClick={this.getInput1Vaule}>获取第一个input值</button>
<input ref={this.input2}></input>
</div>
)
}
}
ReactDOM.render(<GetInputValue />, document.getElementById('test'))