【问题标题】:React state from HOC and component来自 HOC 和组件的反应状态
【发布时间】:2017-01-05 23:27:10
【问题描述】:

我有一个表单,其中包含通过高阶组件管理的受控输入。结构是这样的:

字段高阶组件

function BaseField(WrappedComponent) {
  class WrappedField extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        value: '',
        active: false,
      }
    }

    setValue = (e) => {
      this.setState({ value: e.target.value })
    }
    ...
    <WrappedComponent
      {...this.props}
      value={this.state.value}
      set={this.setValue}
      active={this.state.active}
    />
    ....

字段

import React from 'react';
import BaseField from './BaseField';

const TextField = (props) => {
  return <input
    value={props.value}
    onChange={props.set}
    name={props.name}
    type={props.type}
  />
}

export default BaseField(TextField);

当使用TextField 时效果很好 - 但是,我想更灵活地使用它 - 例如,我希望能够在某些情况下增强 onChange 功能,始终让它设置状态但让它根据使用TextField的组件中的状态或函数做其他事情。

我是否误解了 HOC 的工作原理?

【问题讨论】:

    标签: reactjs jsx higher-order-components


    【解决方案1】:

    您可以使用react-bootstrap 中的createChainedFunction 之类的东西:

    function createChainedFunction(...funcs) {
      return funcs
        .filter(f => f != null)
        .reduce((acc, f) => {
          if (typeof f !== 'function') {
            throw new Error('Invalid Argument Type, must only provide functions, undefined, or null.');
          }
    
          if (acc === null) {
            return f;
          }
    
          return function chainedFunction(...args) {
            acc.apply(this, args);
            f.apply(this, args);
          };
        }, null);
    }
    

    还有我的 react utils 中的一些东西:

    export function copyPropsWithout(props, without) {
      const propKeys = Object.keys(props);
      const passProps = propKeys.reduce((obj, propKey) => {
        if (without.indexOf(propKey) === -1) {
          obj[propKey] = props[propKey];
        }
    
        return obj;
      }, {});
    
      return passProps;
    }
    

    我会将这些添加到您的实用程序中,然后像这样使用它们:

     ...
        <WrappedComponent
          {...copyPropsWithout(this.props, ['onChange'])}
          value={this.state.value}
          set={createChainedFunction(this.setValue, this.props.onChange}}
          active={this.state.active}
        />
        ....
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-02
      • 2018-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-19
      相关资源
      最近更新 更多