在 react-select 上使用 isClearable 时事件为 null

event is null when using isClearable on react-select

我正在通过 react-select Select 组件作为 Material-UI InputBase 组件中的 InputComponent。我已经成功地从选项中填充值,但是,我无法使用 isClearable.

当 isClearable 被触发时,null 被传递给 handleChange(event) 函数,我希望有一种方法可以强制对象通过以防止 null 产生错误。

InputBase 中的 handleChange 函数有 var element = event.target || inputRef.current。由于事件为空,它甚至没有到达将包含所需对象的 inputRef。

最好让它作为一个不受控制的组件工作。

我创建了一个代码框来说明问题:https://codesandbox.io/s/morning-feather-l7xqf

您可以提供您的自定义 onChange() 来捕获 null 并传递您自己的值:

// Deconstruct from otherProps
const SelectWrapper = ({ inputRef, onChange, ...otherProps }) => {
  
  function handleChange(event) {
    // Overwrite the event with your own object if it doesn't exist
    if (!event) {
      event = {
        target: inputRef,
        value: '',
      };
    }
    onChange(event);
  }
  
  return (
    // Pass in the custom handleChange
    <Select styles={customStyle} isClearable ref={inputRef} onChange={handleChange} {...otherProps} />
  );
};