[英]How to pass props to custom components in react-select
我正在嘗試使用自定義組件作為 react-select 中的輸入字段。 因為我需要驗證,所以我嘗試使用 HTML5 oninvalid
(JSX 中的onInvalid
)作為我的輸入標簽,並為oninvalid
設置自定義消息。 但是我無法將消息作為道具傳遞給我在選擇中設置的組件。 下面是我的代碼。
輸入.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')
);
任何人都可以讓我知道我做錯了什么。
不確定您是否已經找到了解決方案,但我設法使用箭頭函數傳遞了我的自定義道具
<Select
closeMenuOnSelect={true}
options={colourOptions}
components={{
Input: (inputProps: InputProps) => (
<components.Input {...inputProps} />
),
}}
/>
最好通過選擇傳遞自定義道具:
props.selectProps
避免每次Select更新時都重新創建Custom組件,可能會導致意外的bug。
在我的情況下,我以這種方式傳遞錯誤:
<Select
defaultValue={values}
selectProps={{ errors }}
isMulti
options={inventoryList}
onChange={changeTreeElement}
// @ts-ignore
styles={colourStyles}
/>
然后訪問它像selectProps.selectProps.errors
在colourStyles方法。
我沒有解決方案(我也在尋找相同的東西),但是您的示例有多個錯誤。
要加載輸入,您必須編寫components={{ Input: InputBoxWithText }}
,因為Input
的組件名稱不是InputBoxWithText
。
此外onInvalid
似乎不是Input
API 的一部分,因此它永遠不會觸發。 您是否嘗試使用<input oninvalid="" />
..?
在版本 5 中,將自定義道具與打字稿一起使用的唯一方法是使用模塊擴充。
所以在我的項目中,我打開了 react-app-env.d.ts 並添加了這個:
import { GroupBase } from 'react-select'
declare module 'react-select/dist/declarations/src/Select' {
export interface Props<Option, IsMulti extends boolean, Group extends GroupBase<Option>> {
customOnClear: () => void;
}
}
您將 prop 傳遞給 select,如下所示:
import Select from "react-select";
<Select customOnClear={() => {/* Your custom clear */} />
並像這樣在您的自定義組件中使用它:
const ClearIndicator = ({ selectProps }: ClearIndicatorProps<Option, false>) => {
const { customOnClear } = selectProps
return <InputClear onClick={customOnClear} />
}
文檔: https ://react-select.com/typescript#custom-select-props
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.