如何在 React material-ui 的自动完成中实现最小字符长度功能

How to achieve minimum character length feature in react material-ui's autocomplete

我想在 React material-ui autocomplete 组件中实现 'min-character-length' 功能。

下面是代码。

constructor(props) {
    super(props);
    this.state = {
      // based on this value, trying to maintain autocomplete's menu state open/close
      shouldOpenList: false, 
    };
  }

// Method in-built
onUpdateInput(searchText, dataSource, params) {

  if( searchText && searchText.length >= 3) {
      this.setState({
          shouldOpenList: true
      })
  }
}

//component props

<AutoComplete 
    hintText={props.placeholder}
    dataSource={ props.data }
    dataSourceConfig={ {text: props.text, value: props.value}  }
    className="fabric-autocomplete form-control"
    disableFocusRipple={false}
    filter={filter}
    onNewRequest={ this.onNewRequest.bind(this) }
    onUpdateInput={ this.onUpdateInput.bind(this) }
    open={this.state.shouldOpenList} // state's value used to show menu
/>

到目前为止,我所了解的是函数 onUpdateInput() 在每次键入时都会被触发,并且它会明确显示菜单。道具 'open' 无法处理状态 'shouldOpenList' 值。

如何实现此组件的最小字符长度功能?

提前感谢您的帮助。

也许你可以尝试 popoverProps={{style: {display: 'none'}}} 之类的东西并用 state.

改变它

在自动完成的 source 中,它使布尔保持打开状态。您的 open prop 只会设置为 componentDidMount 和 componentWillReceiveProps 中的状态。在 componentWillReceiveProps 它检查 this.props.open !== nextProps.open.

所以在这种情况下它会检查 false !== false,这不会触发 setState。我真的不明白为什么他们添加这个 属性 因为它看起来有点没用。也许只在初始渲染时打开它。

调用onUpdateInput 的AutoComplete 的内部handleChange 会在每次添加字符时将组件状态设置为打开。完全无视你的开属性.

编辑:

这个解决方案效果更好

<AutoComplete
  popoverProps={{
    open: this.state.shouldOpenList
  }}
  hintText={props.placeholder}
  dataSource={ props.data }
  dataSourceConfig={ {text: props.text, value: props.value}  }
  className="fabric-autocomplete form-control"
  disableFocusRipple={false}
  filter={filter}
  onNewRequest={ this.onNewRequest.bind(this) }
  onUpdateInput={ this.onUpdateInput.bind(this) }
/>

但是如果长度小于3,你还需要将open设置为false。