mat*_*th5 2 typescript reactjs material-ui
我正在尝试使用 Typescript 将数据从子组件发送到父组件。有很多资源,但很多都没有探索打字稿概念。
在父级上,如何设置 ProductType 事件?这是使用 React.ChangeEvent 的正确方法吗?我们正在使用具有 Material UI 的下拉选择器。
onProductTypeChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setProductType(e.target.value)}
Run Code Online (Sandbox Code Playgroud)
完整代码:
家长:
const ProductExport = () => {
const [productType, setProductType] = useState<undefined | string>('');
return (
<>
<ProductFilters
productTypeValue={productType}
onProductTypeChange={(e: React.ChangeEvent<HTMLInputElement>) =>
setProductType(e.target.value)}
/>
Run Code Online (Sandbox Code Playgroud)
孩子:
type Props = {
productTypeValue?: string;
onProductTypeChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
};
const ProductFilters = ({
productTypeValue,
onProductTypeChange
}: Props) => {
return (
<Box>
<Accordion>
<AccordionSummary>
<Typography>Products</Typography>
</AccordionSummary>
<AccordionDetails>
<Box >
<Box>
<TextField
select
value={productTypeValue}
onChange={onProductTypeChange}
label={'Select Product Type'}
>
Run Code Online (Sandbox Code Playgroud)
通常,您隐藏子级中的内部细节(实际事件),并仅向父级公开结果(新数据):
// Parent
const ProductExport = () => {
const [productType, setProductType] = useState<undefined | string>('');
return (
<ProductFilters
productTypeValue={productType}
onProductTypeChange={setProductType}
/>
);
}
// Child
type Props = {
productTypeValue?: string;
onProductTypeChange?: (newType: string) => void;
};
const ProductFilters = ({
productTypeValue,
onProductTypeChange
}: Props) => {
return (
<TextField
select
value={productTypeValue}
onChange={(event) => onProductTypeChange?.(event.target.value)}
label={'Select Product Type'}
/>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6433 次 |
| 最近记录: |