如何在样式化组件中使用条件呈现,在React中使用样式化组件将我的按钮类设置为活动?

在css中,我会这样做:

<button className={this.state.active && 'active'}
      onClick={ () => this.setState({active: !this.state.active}) }>Click me</button>

如果我try 使用"&amp&amp;'在类名中,它不喜欢它.

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>
     )
  }}

推荐答案

你可以这么做

<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;
  `}
`;

Reactjs相关问答推荐

为什么VScode中的React应用程序无法识别文件夹 struct ?

关于同一位置的不同组件实例的react S规则被视为相同组件

获取点击的国家/地区名称react 映射

使用REACT-RUTER-DOM链接仅更新一个搜索参数

Next.js Next-Auth登录函数重定向到http://localhost:3000/api/auth/error

Mantine DatePickerInput呈现错误

在ReactJS的monaco编辑器中添加美人鱼语法

useEffect firebase 清理功能如何工作?

Chart.js如何go 除边框

如何在一个 Next.js 项目中使用两种布局?

Mui Datepicker 设置了错误的日期

Mui 在 TextField 标签上添加工具提示显示两个工具提示框

根据其中的值不同地react setState 更新状态

有没有办法在用户离开页面时防止输入模糊?

使用 toast 时挂钩调用无效

我应该使用 useEffect 来为 React Native Reanimated 的 prop 值变化设置动画吗?

调用 Jest 和服务方法的问题

如何在 React 中单击鼠标的位置动态添加 div?

react 路由路由加载器不适用于嵌套组件

将 C# Razor 条件块转换为 React.js 代码