React - styled-components,属性和TypeScript

9

我正在研究 styled-components,并尝试从网站上的示例开始,但我也想使用 TypeScript。

这里有一个简单的示例:

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>'

我如何在TypeScript中使用styled-components?


我刚刚正在看这个。 - lomine
这个回答解决了您的问题吗?使用带有Typescript的styled-components时,属性不存在? - Agney
2个回答

22

使用typescript和styled-components:

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;

Edit sweet-pasteur-f3kfe


我现在遇到了你的 CodeSandbox 上的错误,但我的应用程序根本不会显示。错误出现在 index.tsx 中 - Property 'primary' is missing in type '{}' but required in type 'IProps'.ts(2741) - lomine
我在接口中使用了primary?: boolean来修复它。 - lomine

2

我从我的项目中准备了一个例子

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>
);
  1. 你可以从 'index.tsx' 导入接口/类型到 'Wrapper.ts' 中以便重用。

  2. 否则,你可以像这样指定类型:

    export const Wrapper = styled.div<{height:number}>`


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接