代码之家  ›  专栏  ›  技术社区  ›  Knows Not Much

将道具传递给Typescript中的React样式化组件

  •  1
  • Knows Not Much  · 技术社区  · 4 年前

    我用typescript编写了这个样式化的组件。这是根据他们的 documentation

        import matrix from '../img/matrix.jpg';
        const Style = styled.div`
          .fixed {
            background-image: url(${props => props.image ? props.image : "../img/default.jpg"})
            z-index: -999!important;
            display: block;
            top: 0;
            left: 0;
          }
        `;
        export const FixedBackground = () => {return (
          <Style image={matrix}>
          </Style>
        )};
    
    

    但是它抛出了一个编译错误

    Property 'image' does not exist on type 'ThemedStyledProps<Pick<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>, \"slot\" | \"style\" | \"title\" | ... 251 more ... | \"onTransitionEndCapture\"> & { ...; }, any>'

    我还试图编写我的样式组件

        const Style = (props: {image: string}) => {return (styled.div`
          .fixed {
            background-image: url(${props.image})
            z-index: -999!important;
            display: block;
            top: 0;
            left: 0;
          }
        `)};
        export const FixedBackground = () => {return (
          <Style image={matrix}>
          </Style>
        )};
    

    但它再次抛出编译时错误

    Type '{ children: never[]; image: string; }' is not assignable to type 'IntrinsicAttributes & { image: string; }'. Property 'children' does not exist on type 'IntrinsicAttributes & { image: string; }'."

    2 回复  |  直到 4 年前
        1
  •  1
  •   buzatto    4 年前

    试着这样做:

    interface StyleProps {
      image?: string;
    } 
    
    const Style = styled.div<StyleProps>`
          .fixed {
            background-image: url(${props => props.image ? props.image : "../img/default.jpg"})
            z-index: -999!important;
            display: block;
            top: 0;
            left: 0;
          }
        `;
    
        2
  •  0
  •   user3618109    4 年前

    正在查看您发送的链接。我认为它没有被传递,因为您使用的是一个简单的元素,而且由于image属性不是div元素的已知属性,所以它不会被传递。

    上面的部分“通过道具”,“设计任何组件”可能会给你你所需要的。

    传递道具 如果样式化的目标是一个简单的元素(例如。样式.div),样式化组件通过任何已知的HTML属性传递给DOM。如果它是一个自定义的React组件(例如styled(MyComponent)),则styled组件将通过所有props。