如何在样式组件中使用条件呈现,使用React中的样式组件将我的按钮类设置为活动状态?
在CSS中我会这样做:
<button className={this.state.active && 'active'}
onClick={ () => this.setState({active: !this.state.active}) }>Click me</button>
在样式组件中如果我尝试在类名中使用'&&'它不喜欢它.
import React from 'react'
import styled from 'styled-components'
const Tab = styled.button`
width: 100%;
outline: 0;
border: 0;
height: 100%;
justify-content: center;
align-items: center;
line-height: 0.2;
`
export default class Hello extends React.Component {
constructor() {
super()
this.state = {
active: false
}
this.handleButton = this.handleButton.bind(this)
}
handleButton() {
this.setState({ active: true })
}
render() {
return(
<div>
<Tab onClick={this.handleButton}></Tab>
</div>
)
}}
Run Code Online (Sandbox Code Playgroud) 以使用 typescript 创建的 create-react-app 应用程序为例:
npx create-react-app myapp --template typescript
cd myapp
npm install styled-components@5.0.1
Run Code Online (Sandbox Code Playgroud)
然后将样式组件添加到打字稿文件 MyButton.tsx 中。
import React from 'react';
import styled from 'styled-components'; // <<<<< THIS LINE CAUSES ERROR
const MyButtonStyle = styled.button`
background: #9590eb;
border-radius: 3px;
border: none;
color: white;
`;
/**
* MyButton is a wrapper around a Button component. Props/arguments are:
* onClick(event:object) => void
* style: Pass style onto <button> element
*/
function MyButton(props:any) {
return (
<MyButtonStyle style={props.style} type="button" onClick={props.onClick}>{props.children}</MyButtonStyle>
);
} …
Run Code Online (Sandbox Code Playgroud) 我研究了样式组件并尝试了网站上的示例,但我也想使用 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 …
Run Code Online (Sandbox Code Playgroud)