gpt4 book ai didi

reactjs - MaterialUI React 组件上 data-* 属性的 typescript 错误

转载 作者:行者123 更新时间:2023-12-04 01:28:05 24 4
gpt4 key购买 nike

我试图通过 data-testid属性到 Material-UI Select组件,但我收到以下 Typescript 错误:

Type '{ "data-testid": string; }' is not assignable to type 'HTMLAttributes'. Object literal may only specify known properties, and '"data-testid"' does not exist in type 'HTMLAttributes'.

Select.d.ts(111, 3): The expected type comes from property 'SelectDisplayProps' which is declared here on type 'IntrinsicAttributes & SelectProps'



这是由以下代码引起的:
import React from "react";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";

export default function MyComponent() {
return (
<Select SelectDisplayProps={{ "data-testid": "my-component" }}>
<MenuItem value="1">One</MenuItem>
<MenuItem value="2">Two</MenuItem>
<MenuItem value="3">Three</MenuItem>
</Select>
);
}

当 data-* 属性直接传递给组件(例如 <Select data-testid="my-component" /> )时,这似乎不是问题,因此问题在于将其传递给 SelectDisplayProps .

全部 SelectDisplayProps确实是将 Prop 传递给 <Select> 内的子元素( docs )。

我该如何解决这个错误?

最佳答案

您可以找到 SelectDisplayProps 的类型这里:https://github.com/mui-org/material-ui/blob/v4.9.12/packages/material-ui/src/Select/Select.d.ts#L115

SelectDisplayProps?: React.HTMLAttributes<HTMLDivElement>;



您可以根据需要扩展它(以下示例中的 MySelectDisplayProps):
import * as React from "react";
import "./styles.css";
import Select from "@material-ui/core/Select";
import MenuItem from "@material-ui/core/MenuItem";

interface MySelectDisplayProps extends React.HTMLAttributes<HTMLDivElement> {
"data-testid"?: string;
}

function MyComponent() {
const [value, setValue] = React.useState("1");
return (
<Select
value={value}
onChange={event => setValue(event.target.value as string)}
SelectDisplayProps={
{ "data-testid": "my-component" } as MySelectDisplayProps
}
>
<MenuItem value="1">One</MenuItem>
<MenuItem value="2">Two</MenuItem>
<MenuItem value="3">Three</MenuItem>
</Select>
);
}
export default function App() {
return (
<div className="App">
<MyComponent />
</div>
);
}

Edit data attribute in SelectDisplayProps

关于reactjs - MaterialUI React 组件上 data-* 属性的 typescript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61480749/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com