react高階組件小demo-受控組件轉換成非受控組件

高階組件的概念

高階組件是啥呢?就是一個接收組件作爲參數,並返回一個帶有附加的屬性、方法的包裝後的組件。
它的作用就是讓具有相同功能的組件,能夠不寫重複代碼就複用這部分功能,同時這些組件又能夠具有自己獨特的屬性和方法。這或許就是抽象的意思吧。

受控組件、非受控組件

react是單向數據流的,當給表單元素綁定了一個value,那麼就要給這個元素綁定一個onChange事件,在輸入的數據發生變化的時候,去改變value的值。也就是我們看到的輸入框的值,實際上也是輸入-state.value發生改變-輸入框顯示改變,妥妥的單向數據流。
非受控組件就是不要給元素綁定一個value,直接在onChange事件裏面獲取表單的值。

class Input extends React.Component {
    constructor(props) {
        super(props);
        this.onInputEvent = this.onInputEvent.bind(this)
    }
    onInputEvent(event) {
        this.setState({
            value: event.target.value
        })
    }
    render() {
        return <input type="text" value={this.state.value} onChange={this.onInputEvent}/>
    }
}

高階組件封裝受控組件

從受控組件的代碼可以看出來,如果頁面上有多個表單元素,那麼綁定一個value和onChange是所有表單元素共用的功能。所以我們可以把這部分抽出來作爲高階組件,返回一個高階組件包裹後的表單元素。

import React from "react"
function widthInput(WrappedComponent) {
    return class extends React.Component {
        constructor(props) {
            super(props)
            this.state = {
                value: ""
            }
            this.onInputEvent = this.onInputEvent.bind(this)
        }

        onInputEvent(event) {
            this.setState({
                value: event.target.value
            })
        }

        render() {
            const newProps = {
                value: this.state.value,
                onChange: this.onInputEvent
            }
            return <WrappedComponent {...this.props} {...newProps}/>
        }
    }
}

class InputComponent extends React.Component {
    render() {
        return <input type="text" {...this.props} />
    }
}

export default widthInput(InputComponent)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章