【问题标题】:Typescript React.ComponentProps is not getting the propsTypescript React.ComponentProps 没有得到道具
【发布时间】:2021-04-08 14:43:09
【问题描述】:

boxPropprops 中找不到。

库版本:

├─react@16.13.1

└─ styled-components@5.2.1

编辑:https://codesandbox.io/s/jovial-germain-qunlz

【问题讨论】:

    标签: javascript reactjs typescript styled-components


    【解决方案1】:

    这行不通,因为您实际上并没有将任何道具传递给您的 Box 组件,第一行所做的只是注释您的 Box 组件可以使用哪些道具 - 所以 React 没有关于哪些道具的上下文使用ComponentProps方法时提取。

    当您自己注释道具类型时,一个简单的解决方法是执行以下操作:

    type BoxProps = { boxProp: boolean }
    
    const Box = styled('div')<BoxProps>
    
    const MyBox: React.FC<BoxProps> = ({ boxProp }) => {
      return (
        <Box boxProp={boxProp} />
      )
    }
    

    如果有帮助,请告诉我!

    【讨论】:

    • 感谢您的解释。这是我之前在做的,但我想推断道具
    • 不会暴露 styled.div 道具,这正是这里想要的
    【解决方案2】:

    这是我最后一次尝试解决这个问题:

    type OwnProps = { boxProps?: boolean };
    
    const Box = styled.div<OwnProps>``;
    
    type CustomBoxProps = StyledComponentProps<'div', DefaultTheme, OwnProps, never>;
    
    export const MyBox: React.FC<CustomBoxProps> = (props) => {
      return (<Box {...props} />);
    };
    

    很遗憾,必须使用StyledComponentPropsReact.ComponentProps 不适用于 styled-components 界面。他们肯定有问题。

    如果这能解决你的问题,请告诉我,它应该

    【讨论】:

    • 您需要使用这些导入 btw import styled , { StyledComponentProps, DefaultTheme } from 'styled-components'; 只是为了使其更加不言自明
    • 我检查了你的代码框,我的例子在那里工作,所以它应该适合你的用例
    • 感谢您的回答,但我可能不知道Box 后面是哪个样式元素,这意味着'div'StyledComponentProps&lt;'div' 不应被硬编码。另外,如果我使用OwnProps,我可以写const MyBox: React.FC&lt;OwnProps&gt;。使用React.ComponentProps 的全部意义在于推断所有这些类型。
    • 那么您可能没有按照应有的方式使用样式化组件 UI。如果它解决了问题,您可以投票吗?因为这显然是一个可行的解决方案
    猜你喜欢
    • 2020-09-28
    • 2019-01-30
    • 1970-01-01
    • 2021-02-03
    • 2019-12-18
    • 2019-08-13
    • 2017-11-28
    • 1970-01-01
    • 2021-11-26
    相关资源
    最近更新 更多