【问题标题】:using mixins of a react component in es6 style使用 es6 风格的 react 组件的 mixins
【发布时间】:2016-06-06 09:33:36
【问题描述】:

我正在使用一个组件:-https://github.com/christianalfoni/formsy-react,用于创建表单。我正在尝试创建我自己的输入组件之一。所以如上所述我需要使用formy的mixin。但不幸的是,在 es6 风格中不支持它。所以任何人都知道的任何工作。

这是我的组件代码:-

import Formsy from 'formsy-react';

class DropDownAutoComplete extends React.Component {

    constructor(props, context) {
        super(props, context);

       this.mixins = [Formsy.Mixin];
    }

    changeValue(event) {
        this.mixins[0].setValue(event.currentTarget.value);
    }

    handleValue1Change(value) {
        this.setState({value: value});
    }

    render() {

        const className = this.mixins[0].showRequired() ? 'required' : this.mixins[0].showError() ? 'error' : null;

        // An error message is returned ONLY if the component is invalid
        // or the server has returned an error message
        const errorMessage = this.mixins[0].getErrorMessage();
        return <DropdownList
            data={this.props.dropDownConfigs.value}
            onChange={this.changeValue.bind(this)}
            textField={this.props.dropDownConfigs.name}
            caseSensitive={false}
            filter='contains'>
                        </DropdownList>
    }

}

在调用 showRequired 函数时抛出错误。显然它的实现使用了一些状态变量,比如 required。

【问题讨论】:

    标签: reactjs formsy-react


    【解决方案1】:

    By design,mixin 不适用于 ES6 类 - 试图将某些东西组合在一起只会让你头疼!

    一种解决方案是使用所谓的higher-order component - 一个接收组件并返回包裹它的新组件的函数。这些包装器组件可以有自己的生命周期钩子,并且可以将 props 传递给被包装的组件,从而有效地为您提供与 mixins 相同的功能,但可以说是以更简洁的方式!

    formsy-react 允许你采用这种方法,providing its own HOC

    import {HOC} from 'formsy-react';
    
    class MyInput extends React.Component {
      render() {
        return (
          <div>
            <input value={this.props.getValue()} onChange={(e) => this.props.setValue(e.target.value)}/>
          </div>
        );
      }
    };
    export default HOC(MyInput);
    

    【讨论】:

      【解决方案2】:

      您可以使用react-mixin-decorator

      引用自述文件:

      如果你正在使用 ES6 类创建 React 组件并且你喜欢 使用现有的 mixins 为你的 组件,您可能不想花时间来转换 混合到您的 ES6 React 组件类可以使用的东西中。

      【讨论】:

      • formsy-react 实际上是provides a higher-order componenta decorator,而不需要react-mixin-decorator。不过,如果库不提供自己的装饰器,这绝对是一个很好的解决方案!
      • 同意。 This 应该是公认的答案。
      猜你喜欢
      • 2016-09-26
      • 1970-01-01
      • 2017-04-26
      • 2021-06-16
      • 2021-08-11
      • 2017-12-13
      • 2021-03-15
      相关资源
      最近更新 更多