React Higher Order Component强制重新呈现包装组件

时间:2016-08-24 10:16:25

标签: javascript reactjs

我正在努力了解如何在更高阶的组件中正确实现此验证行为。

===========================================

编辑:TLDR:感谢用户@ noa-dev的出色建议,我在这里创建了一个React Fiddle:https://jsfiddle.net/8nLumb74/1/以显示问题。

简单地说:为什么我的文本框在被这个HOC包装时会失去对编辑的关注?

我做错了什么?

文本框组件:

import React from 'react'

export default React.createClass({
    changeText(e) {
        if (this.props.validate)
            this.props.validate(e.target.value)
        this.props.update(e.target.value)
    },
    componentDidMount() {
        console.log('should only be fired once')
    },
    render() {
        return (<input type="text"
            value={this.props.text}
            onChange={this.changeText} />)
    }
})

验证器组件:

import React from 'react'

export default function (WrappedComponent) {
    const Validation = React.createClass({
        validate(text) {
            console.log('validating', text)
        },
        render() {
            return (
                <WrappedComponent
                {...this.props}
                validate={this.validate}
                />
            )
        }
    })
    return Validation
}

父表单组件:

import React from 'react'
import TextBox from './text-box'
import Validator from './validator'

export default React.createClass({
    getInitialState() {
        return ({text: 'oh hai'})
    },
    update(text) {
        this.setState({text})
    },
    render() {
        const ValidatingTextBox = Validator(TextBox)
        return (<ValidatingTextBox
            text={this.state.text}
            update={this.update} />)
    }
})

1 个答案:

答案 0 :(得分:8)

render组件的Form方法中,您每次都会创建一个新的ValidatingTextBox

    render() {
        const ValidatingTextBox = Validator(TextBox)
        return (<ValidatingTextBox
            text={this.state.text}
            update={this.update} />)
    }

相反,您应该创建组件然后使用它,以便维护实例。可能的Form组件如下所示:

import React from 'react'
import TextBox from './text-box'
import Validator from './validator'

const ValidatingTextBox = Validator(TextBox) 

export default React.createClass({
    getInitialState() {
        return ({text: 'oh hai'})
    },
    update(text) {
        this.setState({text})
    },
    render() {
        return (<ValidatingTextBox
            text={this.state.text}
            update={this.update} />)
    }
})
相关问题