一、三个形式
1,字符串形式
通过实例身上的refs来调用,如下代码中的this.refs.input1来调用,这个input1是自己定义的字符串形式。
优点:最简单
缺点:新版本可能不能使用
<script type="text/babel">
class Demo extends React.Component{
showInput1 = () => {
console.log(this);
const {input1} = this.refs
alert(input1.value)
}
showInput2 = () => {
const {input2} = this.refs
alert(input2.value)
}
render(){
return (
<div>
<input type="text" placeholder="提示信息" ref="input1"/>
<button onClick={this.showInput1}>点我展示左侧输入框信息</button>
<input type="text" onBlur={this.showInput2} placeholder="失去焦点提示信息" ref="input2"/>
</div>
)
}
}
ReactDOM.render(<Demo/>,document.getElementById('test'))
</script>
2,回调函数形式
ref={c=>this.input1=c}。这是简写形式。完整形式是ref={(currentNode)=>{this.input1=currentNode}},c是currentNode的简写,代表当前input输入框的节点。这里的input1是直接挂载在组件实例身上的,调用的时候直接通过this.input1来调用3
<script type="text/babel">
class Demo extends React.Component{
showInput1 = () => {
console.log(this);
alert(this.input1.value)
}
showInput2 = () => {
const {input2} = this
alert(input2.value)
}
render(){
return (
<div>
<input type="text" placeholder="提示信息" ref={c=>this.input1=c}/>
<button onClick={this.showInput1}>点我展示左侧输入框信息</button>
<input type="text" onBlur={this.showInput2} placeholder="失去焦点提示信息" ref={c=>this.input2=c}/>
</div>
)
}
}
ReactDOM.render(<Demo/>,document.getElementById('test'))
</script>
3,createRef形式
第一步:创建myRef1 = React.createRef()
第二步:ref={this.myRef1}
第三步:给组件实例身上挂载了myRef1,这个myRef1是一个对象,键是current,值是当前节点。
showData1 = () =>{
alert(this.myRef1.current.value)
}
<script type="text/babel">
class Demo extends React.Component{
myRef1 = React.createRef()
myRef2 = React.createRef()
showData1 = () =>{
alert(this.myRef1.current.value)
}
showData2 = () =>{
alert(this.myRef2.current.value)
}
render(){
return (
<div>
<input type="text" placeholder="提示信息" ref={this.myRef1}/>
<button onClick={this.showData1} >点击提示左侧信息</button>
<input type="text" placeholder="失去焦点提示数据" onBlur={this.showData2} ref={this.myRef2}/>
</div>
)
}
}
ReactDOM.render(<Demo/>,document.getElementById('test'))
</script>