在反应选择上使用 isClearable 时事件为空

Jet*_*chy 3 reactjs react-select material-ui

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

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

InputBase 中的handleChange 函数具有var element = event.target || inputRef.current. 由于 event 为 null,因此它甚至无法访问包含所需对象的 inputRef。

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

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

小智 6

您可以提供您的自定义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} />
  );
};
Run Code Online (Sandbox Code Playgroud)

  • handleChange() 的第二个参数包含一个带有 `action` 属性的对象。当您清除它时,它被设置为“清除”。 (3认同)