I use react-select
in my project.
App.tsx
import "./styles.css";
import React, { useState } from "react";
import Select, { components, OptionProps } from "react-select";
const options = [
{
label: "label 1",
value: "value 1",
dialCode: "dialCode 1"
},
{
label: "label 2",
value: "value 2",
dialCode: "dialCode 2"
}
];
const { Option } = components;
const IconOption = (props: any) => {
const { label, dialCode } = props.data;
return (
<Option {...props}>
<div>{label}</div>
<div>{`(+${dialCode})`}</div>
</Option>
);
};
export default function App() {
const [selected, setSelected] = useState(options[0]);
return (
<Select
options={options}
value={selected}
components={{ Option: IconOption }}
/>
);
}
I use any
type in
const IconOption = (props: any) => {
const { label, dialCode } = props.data;
return (...);
};
When I set the type of the props
to OptionProps
, typescript throws error.
const IconOption = (props: OptionProps) => {
const { label, dialCode } = props.data;
return (...);
};
How to fix it?
Codesandbox
https://codesandbox.io/s/react-typescript-forked-mjo74r?file=/src/App.tsx
Update 1
After adding onChange, the typescript throws error again.
import "./styles.css";
import React, { useState } from "react";
import Select, {
components,
OptionProps,
MultiValue,
SingleValue
} from "react-select";
type OptionData = {
label: string;
value: string;
dialCode: string;
};
const options: OptionData[] = [
{
label: "label 1",
value: "value 1",
dialCode: "dialCode 1"
},
{
label: "label 2",
value: "value 2",
dialCode: "dialCode 2"
}
];
const { Option } = components;
const IconOption = (props: OptionProps<OptionData>) => {
const { label, dialCode } = props.data;
return (
<Option {...props}>
<div>{label}</div>
<div>{`(+${dialCode})`}</div>
</Option>
);
};
export default function App() {
const [selected, setSelected] = useState(options[0]);
const onSelectedChange = (
newValue: MultiValue<OptionData> | SingleValue<OptionData>
) => {
setSelected(newValue);
};
return (
<Select
options={options}
value={selected}
components={{ Option: IconOption }}
onChange={onSelectedChange}
/>
);
}
Codesandbox
https://codesandbox.io/s/react-typescript-forked-mjo74r?file=/src/App.tsx:0-1069
OptionProp
is a generic type. You should declare custom type for option's data and pass it to generic.
type OptionData = {
label: string;
value: string;
dialCode: string
}
const options: OptionData[] = [
{
label: "label 1",
value: "value 1",
dialCode: "dialCode 1"
},
{
label: "label 2",
value: "value 2",
dialCode: "dialCode 2"
}
];
const { Option } = components;
const IconOption = (props: OptionProps<OptionData>) => {
const { label, dialCode } = props.data;
return (
<Option {...props}>
<div>{label}</div>
<div>{`(+${dialCode})`}</div>
</Option>
);
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.