简体   繁体   English

React Material UI v5 样式为 TypeScript

[英]React Material UI v5 styled with TypeScript

Styled typography accepts all the default typography props.样式化排版接受所有默认排版道具。 When I add <ExtraProps> between styled() and the style, it also accepts extra props.当我在 styled() 和样式之间添加 <ExtraProps> 时,它也接受额外的道具。

const StyledTypography = styled(Typography)<ExtraProps>({})

My question is: when I render the styled typography component with prop "component" or "as" it does not accept the dynamic component props.我的问题是:当我使用道具“component”或“as”渲染样式化排版组件时,它不接受动态组件道具。

example:例子:

<StyledTypography component={Link} to="/test">demo</StyledTypography>

(Link is from react-router-dom) (链接来自 react-router-dom)

It can not find the prop "to" that comes from "Link" component and that makes error.它找不到来自“链接”组件的道具“to”,这会出错。 The default Typography accepts component argument Typography<Link>, but the one that extends the default Typography with styled does not.默认 Typography 接受组件参数 Typography<Link>,但使用样式扩展默认 Typography 的参数则不接受。

How to make the styled component accept the new props that come from the dynamic component.如何让样式组件接受来自动态组件的新道具。

(I know that prop as={(props) => <Link to="/test" {...props} /> works, but I do not want it to be like this. It has to be as={Link} and to="/test") (我知道 prop as={(props) => <Link to="/test" {...props} /> 有效,但我不希望它是这样的。它必须是 as={Link } 和 to="/测试")

This这个

styled(Typography)({}) as typeof Typography | FC<ExtraProps>

or this或这个

const StyledTypography: (typeof Typography | FC<ExtraProps>) = styled....

works fine.工作良好。

But it does not feel like the best answer.但这并不是最好的答案。 There should be a better one应该有更好的

Try something like this, make some state="boolean" then try passing the prop down to your styled component.尝试这样的事情,制作一些 state="boolean" 然后尝试将道具传递给您的样式组件。

const [toogle, seToggle] = useState(flase); const [toogle, seToggle] = useState(flase);

const StyledTypography = styled(Typography)({ const StyledTypography = styled(排版)({

background-color: ${(props) =>背景色:${(props) =>

   (props?.cardToggle ? 'lightgrey' : 'white')};

})` })`

<StyledTypography onclick={()=> setToggle(!toggle)} toggle={toggle} component={Link} to="/test">demo</StyledTypography>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM