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> ) } }