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