一. 字符串形式調用(簡單,但是效率低,在未來的版本中可能會廢棄,不推薦使用)
//創建類式組件 class Demo extends React.Component{ render(){ return ( <div> <input type='text' placeholder="點擊按鈕提示" id="aa"/> <button onClick={this.showData}>顯示提示效果</button> <input ref='aa1' type='text' onBlur={this.showData1} placeholder="失去按鈕提示" id="aa1"/> </div> /* 組件內的標簽可以定義ref來標識自己,會在組件的實例對象的this.refs屬性中找到 */ ) } showData = ()=>{ let v = document.querySelector("#aa").value; alert(v); } showData1 = ()=>{ let v = document.querySelector("#aa1").value; console.log(this); let v1 = this.refs.aa1.value; console.log(v,"--",v1); /*不建議使用它,因為 string 類型的 refs 存在 一些問題。它已過時并可能會在未來的版本被移除。 一句話總結: 效率不高 */ } } //渲染組件到頁面 ReactDOM.render(<Demo/>, document.querySelector("#test"));
二. 回調函數調用(簡單好用,使用頻率高)
//創建類式組件 class Demo extends React.Component{ render(){ return ( <div> <input ref={(currentNode)=>{this.input1=currentNode}} type='text' placeholder="點擊按鈕提示" id="aa"/> <button onClick={this.showData}>顯示提示效果</button> <input ref={c=>this.input2=c} type='text' onBlur={this.showData1} placeholder="失去按鈕提示" id="aa1"/> </div> /* 以上兩種ref的賦值方式屬于: 回調函數 */ ) } showData = ()=>{ console.log(this.input1.value); } showData1 = ()=>{ console.log(this.input2.value); } }
二. React.createRef() 調用(官方推薦)
//創建類式組件 //創建類式組件 class Demo extends React.Component{ myRef = React.createRef() myRef2 = React.createRef() //React.createRef調用后可以返回一個容器,該容器可以存儲被ref所標識的節點,該容器是"專人專用" //推薦 ref方法 render(){ return ( <div> <input ref={this.myRef} type='text' placeholder="點擊按鈕提示" id="aa"/> <button onClick={this.showData}>顯示提示效果</button> <input ref={this.myRef2} type='text' onBlur={this.showData1} placeholder="失去按鈕提示" id="aa1"/> </div> ) } showData = ()=>{ let input1 = this.myRef.current; console.log(input1.value); } showData1 = ()=>{ console.log( this.myRef2.current.value); } }