react 中ref的3種用法



1.字符串
通過 this.refs.test 來引用真實dom的節點
dom 節點上使用

<input type ="text" ref="test"/> 

 

2.回調函數
回調函數就是在dom節點或組件上掛載函數,函數的入參是dom節點或組件實例,達到的效果與字符串形式是一樣的,
都是獲取其引用。

<input type="text" ref={(input)=>{this.textInput=input}} 

 

3.React.createRef()
在React 16.3版本后,使用此方法來創建ref。將其賦值給一個變量,通過ref掛載在dom節點或組件上,該ref的current屬性將能拿到dom節點或組件的實例

class Counter extends Component {
constructor() {
super()
this.state ={sum:0,number:0}
this.myRef = React.createRef();
}
change = () =>{
this.setState({...this.state,sum: Number(this.textInput.value) + Number(this.myRef.current.value)})
}
componentDidMount(){
console.log(this.myRef.current.value);
}
render() {
return (
<div onChange ={this.change} >
<input type="text" ref={(input)=>{this.textInput=input}} />+ 
<input type ="text" ref={this.myRef} /> = {this.state.sum}
</div>

)
}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM