React學習day05_ref
- 轉發refs react當中提供了一個ref的數據,表示當前組件的真正實例的引用(不能在無狀態組件當中來進行使用 因爲無狀態組件沒有實例)
- 有三種方式 進行 ref的使用
- 字符串的方式
- 回調函數,就是在dom節點上掛載函數,入參形參
- React.createRef()
- 官方建議我們 不要過度使用 refs 需要優先考慮state
- 當給 HTML 元素添加 ref 屬性時,ref 回調接收了底層的 DOM 元素作爲參數。
- 當給組件添加 ref 屬性時,ref 回調接收當前組件實例作爲參數。
- 當組件卸載的時候,會傳入null
<div id="reactDom"></div>
<script type="text/babel">
class Com extends React.Component {
constructor(props){
super(props)
this.myRef = React.createRef();
}
fun = () => {
console.log(this.myRef.current.value)
}
render() {
return (
<div>我是組件
{}
{}
<input type="text" ref={this.myRef} placeholder="請輸入"/>
<button onClick={this.fun}>點我得到輸入框的值</button>
</div>
)
}
}
ReactDOM.render(<Com />, document.getElementById("reactDom"))
</script>