简体   繁体   中英

React - styled-components, props, and TypeScript

I looking into styled-components and trying the examples from the website but I also wanted to use TypeScript.

I have this simple example here

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;

but I'm getting errors on the primary prop

I getting the error

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

Ho can I use styled-components with TypeScript?

Use styled-components with typescript:

const Button = styled.button<{ primary?: boolean }>`

Full code:

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;

编辑 sweet-pasteur-f3kfe

I prepare a example from my project

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. you can import interface/type from 'index.tsx' to 'Wrapper.ts' to reuse.

  2. other wise you can specify type like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM