React:是否可以在容器组件中调用高阶组件?

React: Is it possible to call a higher-order component within a container component?

在我的代码库中,我有一个高阶组件 (HOC),用于将所有输入验证功能添加到给定组件。它在像这样定义的组件上使用时效果很好...

let NameInput = React.createClass({
    render() {
        return (
            <div>
                <label htmlFor="name-input">Name</label>
                <input name="name-input" />
            </div>
        );
    }
});

let NameInput = addInputValidation(NameInput);

module.exports = NameInput;

但我现在需要根据来自服务器的数组定义一系列输入。像这样...

let TestApp = React.createClass({
    render() {
        // Pretend the names array came from the server and is actually an array of objects.
        let names = ['First name', 'Middle name', 'Last name'];

        // Map over our names array in hopes of ending up with an array of input elements
        let nameComponents = names.map((name, index) => {
            let componentToRender = (
                    <div key={index}>
                        <label htmlFor={name}>{name}</label>
                        <input name={name} />
                    </div>
            );

            // Here is where I'd like to be able to use an HOC to wrap my name inputs with validation functions and stuff
            componentToRender = addInputValidation(componentToRender);

            return componentToRender;
        })


        return (
            <div>
                <p>Enter some names:</p>
                {nameComponents}
            </div>
        );
    }
})

let addInputValidation = function(Component) {
    let hoc = React.createClass({
        getInitialState() {
            return {
                isValid: false
            };
        },
        render() {
            return (
                <div>
                    <Component {...this.props} />
                    {this.state.isValid ? null : <p style={{color: "red"}}>Error!!!!</p>}
                </div>
            );
        }
    });

    return hoc;
}

module.exports = TestApp;

当您尝试呈现从另一个组件中调用 HOC 的结果时,React 不喜欢它。

我认为这与我的 componentToRender 不是真正的 React 组件或其他东西有关。

所以我的问题是...

为什么我不能从另一个组件中调用 HOC?

有没有办法在数组的每个元素上调用 HOC?

这是一个可能有用的 jsfiddle:https://jsfiddle.net/zt50r0wu/

编辑以澄清一些事情:

我映射的数组实际上是描述输入细节的对象数组。包括输入类型(select、复选框、文本等)。

还有我的 addInputValidation HOC 实际上比组件接受更多的参数。它需要一组商店索引,这些索引将从 Redux 商店中提取以用于验证。这些存储索引源自描述输入的对象数组中的信息。能够访问这个潜在的动态数组是我希望能够在 React 生命周期内调用我的 HOC 的原因。

所以映射我的输入数组可能看起来更像这样...

let Select = require('components/presentational-form/select');
let Text = require('components/presentational-form/select');
let CheckboxGroup = require('components/presentational-form/select');
let TestApp = React.createClass({
    render() {
        // Pretend the inputs array came from the server
        let inputs = [{...}, {...}, {...}];
        // Map over our inputs array in hopes of ending up with an array of input objects
        let inputComponents = inputs.map((input, index) => {    
            let componentToRender = '';

            if (input.type === 'select') {
                componentToRender = <Select labelText={input.label} options={input.options} />;
            } else if (input.type === 'text') {
                componentToRender = <Text labelText={input.label} />;
            } else if (input.type === 'checkbox') {
                componentToRender = <CheckboxGroup labelText={input.label} options={input.options} />;
            }

            // Here is where I'd like to be able to use an HOC to wrap my name inputs with validation functions and stuff
            componentToRender = addInputValidation(componentToRender, input.validationIndexes);

            return componentToRender;
        })


        return (
            <div>
                <p>Enter some names:</p>
                {inputComponents}
            </div>
        );
    }
})

关于您的编辑:问题仍然是您从 .map 回调中返回一个组件而不是一个元素。但这可以通过更改

轻松解决
return componentToRender;

return React.createElement(componentToRender);

您的代码中存在的问题是:

  • addInputValidation 期望传递一个 component 但你传递给它的是一个 element (<div />) .
  • JSX 期望传递一个(数组)元素,但你传递给它的是一个组件数组。

看来解决问题的最简单方法是创建一个通用 Input 组件,该组件接受名称和值作为 prop:

let Input = React.createClass({
    render() {
        return (
            <div>
                <label htmlFor={this.props.name}>{this.props.name}</label>
                <input name={this.props.name} />
            </div>
        );
    }
});

module.exports = addInputValidation(Input);

用作

let nameComponents = names.map((name, index) => <Input key={index} name={name} />);

我认为您被绊倒的是组件与元素之间的区别。我发现将组件视为函数并将元素视为该函数的结果很有帮助。因此,您真正要做的就是有条件地选择三个不同函数之一,将一些参数传递给它,然后显示结果。我相信你想要这样的东西:

(这可以清理,顺便说一句,只是尽量保留你的代码结构)

let Select = require('components/presentational-form/select');
let Text = require('components/presentational-form/select');
let CheckboxGroup = require('components/presentational-form/select');
let TestApp = React.createClass({
    render() {
        // Pretend the inputs array came from the server
        let inputs = [{...}, {...}, {...}];
        // Map over our inputs array in hopes of ending up with an array of input objects
        let inputComponents = inputs.map((input, index) => {    
            let ComponentToRender;
            let props;            

            if (input.type === 'select') {
                ComponentToRender = addInputValidation(Select);
                props = { labelText: input.label, options: input.options };
            } else if (input.type === 'text') {
                ComponentToRender = addInputValidation(Text);
                props = { labelText: input.label };
            } else if (input.type === 'checkbox') {
                ComponentToRender = addInputValidation(CheckboxGroup);
                props = { labelText: input.label, options: input.options };
            }

            let element = <ComponentToRender {...props} />;

            return element;
        })


        return (
            <div>
                <p>Enter some names:</p>
                {inputComponents}
            </div>
        );
    }
})

是的,当然有办法。但是一般来说,HOC 是一种非常痛苦的处理验证的方法。

There is a different approach to validation, based on ValueLink pattern.

只需将生成的代码与高阶组件方法进行比较。