如何在 react-select 中将 props 传递给自定义组件

IT技术 javascript reactjs react-select
2021-05-07 13:16:27

我正在尝试使用自定义组件作为 react-select 中的输入字段。由于我需要验证,因此我尝试将 HTML5 oninvalidonInvalid在 JSX 中)用于我的输入标记,并为oninvalid. 但是,我无法将消息作为props传递给我在 select 中设置的组件。下面是我的代码。

输入.js

import React from "react";
import { components } from "react-select";

export default class Input extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    console.log("component mounted");
  }
  setInvalidMessage = event => {
    event.target.setCustomValidity("Custom Message");
  };

  render() {
    if (this.props.isHidden) {
      return <components.Input {...this.props} />;
    }
    return (
      <components.Input
        {...this.props}
        required
        onInvalid={this.setInvalidMessage}
      />
    );
  }
}

例子.js

import React from "react";
import Input from "./Input";
import Select from "react-select";
import { colourOptions } from "./docs/data";

const InputBoxWithText = props => {
  return <Input {...props} />;
};

export default () => (
  <form>
    <Select
      closeMenuOnSelect={true}
      components={{ InputBoxWithText }}
      options={colourOptions}
    />
    <input type="submit" />
  </form>
);

如果我在 components 属性中传递 Input,我会在 Input.js 中得到硬编码的消息。如果我通过 InputBoxWithText 我根本看不到 Input 安装。

索引.js

import React from 'react';
import ReactDOM from 'react-dom';
import Example from './example';

ReactDOM.render(
<Example />,
document.getElementById('root')
);

这是CodeSandBox.io 网址

任何人都可以让我知道我做错了什么。

4个回答

最好通过选择传递自定义props:

props.selectProps

避免每次Select更新时都重新创建Custom组件,可能会导致意外的bug。

不确定您是否已经找到了解决方案,但我设法使用箭头函数传递了我的自定义props

<Select
  closeMenuOnSelect={true}
  options={colourOptions}
  components={{
    Input: (inputProps: InputProps) => (
      <components.Input {...inputProps} />
    ),
  }}    
/>

就我而言,我以这种方式传递错误:

        <Select
            defaultValue={values}
            selectProps={{ errors }}
            isMulti
            options={inventoryList}
            onChange={changeTreeElement}
            // @ts-ignore
            styles={colourStyles}
        />

然后像selectProps.selectProps.errorscolourStyles 方法中一样访问它

我没有解决方案(我也在寻找相同的东西),但是您的示例有多个错误。

要加载输入,您必须编写components={{ Input: InputBoxWithText }},因为组件名称Input不是InputBoxWithText

另外,onInvalid似乎没有成为部分InputAPI,所以它永远不会触发。您是否尝试使用<input oninvalid="" />..?