refs屬性
- 概念:組件三大屬性之一,唯一標(biāo)識,可以操作真實(shí)DOM
// refs屬性,通過操作虛擬DOM來操作真實(shí)DOM
class App extends React.Component{
// 構(gòu)造方法,繼承父組件
constructor(props){
super(props); // 調(diào)用父組件的屬性
this.handleclick = this.handleclick.bind(this) // 組件中自定義的方法需要強(qiáng)制綁定this
}
// 自定義組件方法
handleclick(){
let val = this.refs.val.value;
alert(val)
}
handleblur(event){
// event當(dāng)前事件的回調(diào)函數(shù),target指向當(dāng)前事件的對象
alert(event.target.value)
}
render() {
return (
<div>
<input ref="val" /> {/* 定義ref屬性來標(biāo)識標(biāo)簽,方便操作dom */}
<button onClick={this.handleclick}>點(diǎn)擊彈出輸入框內(nèi)容</button> {/* 綁定點(diǎn)擊事件 */}
<input onBlur={this.handleblur} placeholder="失去焦點(diǎn)事件,event回調(diào)"/>
</div>
)
}
}
// 渲染
ReactDOM.render(<App />,document.getElementById("example") )
注意:點(diǎn)擊事件沒有用event回調(diào)函數(shù)是因?yàn)?,事件在button上而獲取的數(shù)據(jù)在另一個DOM上