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