How can I use conditional rendering in styled-components to set my button class to active using styled-components in React?
In css I would do it similarly to this:
<button className={this.state.active && 'active'}
onClick={ () => this.setState({active: !this.state.active}) }>Click me</button>
In styled components if I try to use '&&' in the classname it doesn't like it.
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>
)
}}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…