方法
- stateのbooleanを更新したら、styled-componentで動的に変更する
キャプチャー
こんな感じのボタンを作成 クリックしたら文字色が赤になる様にします
ボタンをクリックしたら文字が赤くなる
ソース
アプリケーション側
import RoundButton from './components/RoundButton' class App extends React.Component { constructor(props) { super(props) this.state = { isClicked: false } } hendleClick() { this.setState({isClicked: !this.state.isClicked}) } render() { return ( <div> <RoundButton isClicked={this.state.isClicked} onClick={() => this.hendleClick()} > クリック </RoundButton> </div> ) } } export default App
ボタンのjs
ポイントは関数の中で、propsを受け取れるらしい(変数名はなんでも良い)
import styled from 'styled-components' const RoundButton = styled.div` width: 100px; height: 50px; background-color: black; color: ${(props) => (props.isClicked ? 'red' : 'white')}; border-radius: 5px; text-align: center; line-height: 50px; ` export default RoundButton