如何使用styles HoC用material-ui实现ag-grid自定义浮动过滤器?

时间:2019-05-15 12:44:05

标签: material-ui ag-grid ag-grid-react

创建了一个带有验证的ag-grid定制浮动过滤器,当验证失败时,需要使用withStyles高阶组件(HoC)对材质用户界面主题类进行过滤。但是,当您使用HoC onParentModelChanged包装自定义浮动过滤器时,根本不会被调用。

使用硬编码样式设置元素样式属性,但是在主题项目中使用@ material-ui / core v1.4.0不允许这样做。 以下是我使用验证和硬编码样式创建的自定义浮动过滤器。

import { PropTypes } from 'prop-types';

import styles from './styles';

const DEFAULT_MIN_CHARS = 3;
const ENTER_KEY = 13;

export class CustomFloatingFilter extends Component {
  constructor(props) {
    super(props);

    this.state = {
      currentValue: '',
      minChars: props.minChars ? props.minChars : DEFAULT_MIN_CHARS,
      invalidFilter: false,
      styles: styles()
    };
    this.keyPressed = this.keyPressed.bind(this);
    this.valueChanged = this.valueChanged.bind(this);
    this.onParentModelChanged = this.onParentModelChanged.bind(this);
    this.onFloatingFilterChanged = change => {
      const { minChars } = this.state;
      if(change && change.model && (!change.model.filter || change.model.filter.length >= minChars)) {
        return props.onFloatingFilterChanged(change);
      }
      return false;
    };
  }

  keyPressed(event) {
    this.setState(
      { enterPressed: event.which === ENTER_KEY },
      () => {
        const { enterPressed } = this.state;
        if(enterPressed) { //update filter only when enter. valueChanged will handle all other cases
          this.onFloatingFilterChanged(this.buildChanged());
        }
      }
    );
  }

  valueChanged(event) {
    const { minChars } = this.state;
    this.setState(
      {
        currentValue: event.target.value,
        invalidFilter: !!event.target.value && event.target.value.length < minChars
      },
      () => {
        this.onFloatingFilterChanged(this.buildChanged());
      }
    );
  }

  onParentModelChanged(parentModel) {
    this.setState({ currentValue: parentModel ? parentModel.filter : '' });
  }

  buildChanged() {
    const { currentValue, enterPressed, invalidFilter } = this.state;

    return {
      model: {
        filterType: 'text',
        type: 'equals',
        filter: currentValue
      },
      apply: !invalidFilter && (enterPressed || currentValue === '') //for applyButton:true case
    };
  }

  render() {
    const { currentValue, invalidFilter, styles } = this.state;

    return (
      <div style={invalidFilter ? styles.invalid : {} //eslint-disable-line
      //withStyles HoC doesn't work with ag-grid floating filter component
      }
      >
        <input className='ag-floating-filter-input' onKeyPress={this.keyPressed} onChange={this.valueChanged} value={currentValue} />
      </div>
    );
  }
}

CustomFloatingFilter.propTypes = {
  minChars: PropTypes.number,
  onFloatingFilterChanged: PropTypes.func
};

export default CustomFloatingFilter;

0 个答案:

没有答案