1.string类型的ref已经过时了
2.使用回调形式的ref
class Demo extends React.Component{
render(){
return(
<div>
<input ref={(currentNode)=>{this.input1=currentNode}} type="text" placeholder="点击按钮提示数据"/>
<button onClick={this.showLeft}>点我提示左侧数据</button>
<input ref="input2" onBlur={this.showData} type="text" placeholder="失去焦点提示数据"/>
</div>
)
}
showLeft=()=>{
const {result}=this
alert(result.value)
}
showData=()=>{
const {data}=this
alert(data.value)
}
}
ReactDOM.render(<Demo/>,document.getElementById('test'))
这种回调的ref之直接写在标签内部,内联函数,在进行更新时会进行两次回调函数的执行其中第一次传入参数null,第二次会传入当前所处的DOM元素节点。使用以下方式可以解决:
<input ref={this.saveInput} type="text"/>
class Demo extends React.Component{
state = {isHot:false}
showInfo = ()=>{
const {input1} = this
alert(input1.value)
}
changeWeather = ()=>{
//获取原来的状态
const {isHot} = this.state
//更新状态
this.setState({isHot:!isHot})
}
saveInput = (c)=>{
this.input1 = c;
console.log('@',c);
}
render(){
const {isHot} = this.state
return(
<div>
<h2>今天天气很{isHot ? '炎热':'凉爽'}</h2>
{/*<input ref={(c)=>{this.input1 = c;console.log('@',c);}} type="text"/><br/><br/>*/}
<input ref={this.saveInput} type="text"/><br/><br/>
<button onClick={this.showInfo}>点我提示输入的数据</button>
<button onClick={this.changeWeather}>点我切换天气</button>
</div>
)
}
}
//渲染组件到页面
ReactDOM.render(<Demo/>,document.getElementById('test'))
使用createRef()方法
class Demo extends React.Component{
//该容器是专人专用的
//React.createRef()调用后会返回一个容器,存储被ref所标识的节点
myRef=React.createRef()
render(){
return(
<div>
<input ref={this.myRef} type="text" placeholder="点击按钮提示数据"/>
<button onClick={this.showLeft}>点我提示左侧数据</button>
</div>
)
}
showLeft=()=>{
// const {result}=this.refs.input1
// alert(result.value)
console.log(this.myRef.current.value)
}
}
ReactDOM.render(<Demo/>,document.getElementById('test'))
</script>