【发布时间】:2018-09-28 08:59:42
【问题描述】:
我正在尝试使用自定义组件作为 react-select 中的输入字段。因为我需要验证,所以我尝试使用 HTML5 oninvalid(JSX 中的 onInvalid)作为我的输入标签,并为 oninvalid 设置自定义消息。但是,我无法将消息作为道具传递给我在选择中设置的组件。下面是我的代码。
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,我会在 Input.js 中获得硬编码消息。如果我通过 InputBoxWithText,我根本看不到 Input 安装。
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Example from './example';
ReactDOM.render(
<Example />,
document.getElementById('root')
);
如果我做错了什么,谁能告诉我。
【问题讨论】:
标签: javascript reactjs react-select