React で styled-components を使用してボタン クラスをアクティブに設定するために、styled-components で条件付きレンダリングを使用するにはどうすればよいでしょうか?
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>
)
}}
ベストアンサー1
これを行うだけで
<Tab active={this.state.active} onClick={this.handleButton}></Tab>
そして、あなたのスタイルは次のようになります:
const Tab = styled.button`
width: 100%;
outline: 0;
border: 0;
height: 100%;
justify-content: center;
align-items: center;
line-height: 0.2;
${({ active }) => active && `
background: blue;
`}
`;