我研究了样式化的组件,并尝试了网站上的示例,但我也想使用打字稿。
我在这里有一个简单的例子
import React from 'react';
import './App.css';
import styled from 'styled-components';
interface IProps{
primary: boolean
}
const App:React.FC<IProps> = ({primary}) => {
return (
<div className="App">
<h1>Styled Components</h1>
<Button>Normal</Button>
<Button primary>Primary</Button>
</div>
);
}
const Button = styled.button`
background: ${props => props.primary ? 'red' : 'white'};
color: ${props => props.primary ? 'white' : 'red'};
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 1px solid green;
border-radius: 3px;
`
export default App;
但是我在主要道具上遇到了错误
我收到错误消息
Property 'primary' does not exist on type 'ThemedStyledProps<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "form" | ... 264 more ... | "onTransitionEndCapture"> & { ...; }, any>'
我可以将带样式的组件与打字稿一起使用
答案 0 :(得分:3)
将带样式的组件与打字稿一起使用:
const Button = styled.button<{ primary?: boolean }>`
完整代码:
import * as React from 'react';
import styled from 'styled-components';
interface IProps{
primary?: boolean
}
const App:React.FC<IProps> = () => {
return (
<div className="App">
<h1>Styled Components</h1>
<Button>Normal</Button>
<Button primary>Primary</Button>
</div>
);
}
const Button = styled.button<{ primary?: boolean }>`
background: ${props => props.primary ? 'red' : 'white'};
color: ${props => props.primary ? 'white' : 'red'};
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border: 1px solid green;
border-radius: 3px;
`
export default App;
答案 1 :(得分:0)
我从我的项目中准备了一个示例
Wrapper.ts(styled-component)
import styled from 'styled-components';
interface Props {
height: number;
}
export const Wrapper = styled.div<Props>`
padding: 5%;
height: ${(props) => props.height}%;
`;
index.tsx
import React, { FunctionComponent } from 'react';
import { Wrapper } from './Wrapper';
interface Props {
className?: string;
title: string;
height: number;
}
export const MainBoardList: FunctionComponent<Props> = ({ className, title, height }) => (
<Wrapper height={height} className={className}>
{title}
</Wrapper>
);
您可以将接口/类型从“index.tsx”导入到“Wrapper.ts”以重复使用。
否则你可以像这样指定类型
export const Wrapper = styled.div<{height:number}>`