React - 样式化组件、道具和 TypeScript

lom*_*ine 2 typescript reactjs 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;
Run Code Online (Sandbox Code Playgroud)

但我在主要道具上遇到错误

我收到错误

Property 'primary' does not exist on type 'ThemedStyledProps<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "form" | ... 264 more ... | "onTransitionEndCapture"> & { ...; }, any>'
Run Code Online (Sandbox Code Playgroud)

我可以在 TypeScript 中使用样式组件吗?

kei*_*kai 7

将样式组件与打字稿一起使用:

const Button = styled.button<{ primary?: boolean }>`
Run Code Online (Sandbox Code Playgroud)

完整代码:

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;
Run Code Online (Sandbox Code Playgroud)

编辑 sweet-pasteur-f3kfe