Component强制重新呈现包装组件

Component强制重新呈现包装组件

本文介绍了React Higher Order Component强制重新呈现包装组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am struggling to understand how to correctly implement this validation behaviour in a higher order component.

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

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

编辑:TLDR:谢谢user @ noa-dev的优秀建议我在这里创建了一个React Fiddle:显示问题。

TLDR: Thanks to user @noa-dev 's excellent suggestion I have created a React Fiddle here: https://jsfiddle.net/8nLumb74/1/ to show the issue.

我做错了什么?

文本框组件:

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} />)
    }
})


推荐答案

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

In the render method of the Form component, you are creating a new ValidatingTextBox every time:

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

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

Instead, you should make the component and then use it so the instance gets maintained. A possible Form component would look like:

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} />)
    }
})

这篇关于React Higher Order Component强制重新呈现包装组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 08:48