如何在样式化组件中使用条件呈现,在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相关问答推荐

如何处理具有REACTION-REDUX状态的Nextjs路由警卫

错误./src/TopScroll.js 31:21-31导出';(作为';随路由导入)在';Reaction-Router-Dom';中找不到

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

react 挂钩-使用有效澄清

在url中使用MongoDB对象ID被认为是不好的做法?

如何使ionic 面包屑在州政府条件下可点击?

使用Ionic 7和React 18,如何访问历史对象以在页面之间导航?

svg每条路径上的波浪动画

React路由dom布局隐藏内容

如何在我的 React 应用程序中仅显示我的 Register 组件

在 React 中,为什么不将组件和钩子结合起来呢?

我发送的 prop 的值不会改变.如果成功登录,导航栏中的 prop 必须为 true.我从后端得到 200 ok

Reactjs:MUI5:MobileDateTimePicker API:如何自定义日历中的文本

在react的useEffect钩子中,我的函数被调用,但只有第一个函数能够改变状态,第二个函数无法改变状态.

如何在PrimeReact的表格中修改筛选图标功能

如何在next.js 13中仅在主页导航栏上隐藏组件?

图像路径很奇怪,部署 Next.js 应用程序后我看不到任何图像

React Router v6 - 访问嵌套路由和处理手写 url 的正确方法

如何将 id 从页面传递到另一个页面?

点击提交后自动添加#