react 中ref的3種用法
阿新 • • 發佈:2020-07-09
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> ) } }