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

Input.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}
      />
    );
  }
}

example.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>
);

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

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

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

这是CodeSandBox.io URL

谁能让我知道我在做什么错。

最佳答案

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

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

而且onInvalid似乎不是Input API的一部分,因此它将永远不会触发。您是否要使用<input oninvalid="" /> ..?

10-01 04:05
查看更多