首页 > 解决方案 > 在 react-select 上使用 isClearable 时事件为空

问题描述

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

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

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

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

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

标签: reactjsmaterial-uireact-select

解决方案


您可以提供您的自定义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} />
  );
};

推荐阅读