React學習05_ref

React學習day05_ref

  1. 轉發refs react當中提供了一個ref的數據,表示當前組件的真正實例的引用(不能在無狀態組件當中來進行使用 因爲無狀態組件沒有實例)
  2. 有三種方式 進行 ref的使用
    1. 字符串的方式
    2. 回調函數,就是在dom節點上掛載函數,入參形參
    3. React.createRef()
  3. 官方建議我們 不要過度使用 refs 需要優先考慮state
  4. 當給 HTML 元素添加 ref 屬性時,ref 回調接收了底層的 DOM 元素作爲參數。
  5. 當給組件添加 ref 屬性時,ref 回調接收當前組件實例作爲參數。
  6. 當組件卸載的時候,會傳入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.refs.demoInput.value)
            console.log(this.myRef.current.value)
        }
        render() {
            return (
                <div>我是組件
                    {/*<input type="text" ref="demoInput" placeholder="請輸入"/>
                    <button onClick={this.fun}>點我得到輸入框的值</button>*/}
                    {/*<input type="text" ref={(input)=>{this.textinput = input}} placeholder="請輸入"/>
                    <button onClick={this.fun}>點我得到輸入框的值</button>*/}

                    <input type="text" ref={this.myRef} placeholder="請輸入"/>
                    <button onClick={this.fun}>點我得到輸入框的值</button>
                </div>
            )
        }
    }
    ReactDOM.render(<Com />, document.getElementById("reactDom"))
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章