这是我的风格组件。
import * as React from 'react';
import styled from 'styled-components';
import { ComponentChildren } from 'app-types';
interface Props {
children: ComponentChildren;
emphasized: boolean;
}
const HeadingStyled = styled.h2`
${props => props.emphasized && css`
display: inline;
padding-top: 10px;
padding-right: 30px;
`}
`;
const Heading = (props: Props) => (
<HeadingStyled>
{props.children}
</HeadingStyled>
);
export default Heading;
我得到警告:
Property 'emphasized' does not exist on type 'ThemedStyledProps<DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>, any>'.
Cannot find name 'css'. Did you mean 'CSS'?
我怎样才能让它发挥作用?
styled("h2")<IProps>
。您可以从documentation了解更多关于模式的信息css
,当你需要从函数实际返回CSS时,它被添加为帮助器。看看conditional rendering。考虑到这些因素,该组件变为:
const HeadingStyled = styled("h2")<{emphasized: boolean}>`
${props => props.emphasized && `
display: inline;
padding-top: 10px;
padding-right: 30px;
`}
`;
之前的回答对我有用,但只是添加一些对我的情况也有帮助的信息:
StyledComponents使用“ThemedStyledFunction”接口,允许用户定义其他Prop类型。
这意味着你可以创建一个界面,如:
interface HeadingStyled {
emphasized: boolean;
}
并在组件上使用它:
const HeadingStyled = styled("h2")<HeadingStyled>`
${props => props.emphasized && `
display: inline;
padding-top: 10px;
padding-right: 30px;
`}
`;
(如果您有多个道具,这是实现@BoyWithSilverWings建议的更简洁的方法)
查看此讨论以获取更完整的信息:
https://github.com/styled-components/styled-components/issues/1428#issuecomment-358621605