gpt4 book ai didi

reactjs - React - 样式化组件、 Prop 和 TypeScript

转载 作者:行者123 更新时间:2023-12-04 15:59:49 31 4
gpt4 key购买 nike

我研究了样式组件并尝试了网站上的示例,但我也想使用 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;
但我在主要 Prop 上遇到错误
我收到错误
Property 'primary' does not exist on type 'ThemedStyledProps<Pick<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, "form" | ... 264 more ... | "onTransitionEndCapture"> & { ...; }, any>'
我可以在 TypeScript 中使用样式组件吗?

最佳答案

将样式组件与 typescript 一起使用:

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

关于reactjs - React - 样式化组件、 Prop 和 TypeScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60992002/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com