如何动态更改样式组件的样式?

How to change style of styled-component dynamically?

我目前正在学习如何在 React 中使用样式化组件,但在实现时遇到了问题。

我有一排按钮(定义为 div)。单击按钮时,我希望它的背景填充某种颜色。所有其他按钮应保持 'unselected'。这是我目前所拥有的:

import React from 'react';
import styles from 'styled-components';

const ButtonsRow = styles.div`
    display: flex;
    justify-content: space-evenly;
`;

const Button = styles.div`
    cursor: pointer;
    :hover {
        background-color: gray;
    }

    background-color: ${props => props.selected ? 'red' : 'none'};
`;

class ButtonsContainer extends React.Component {

    handleClick = (e) => {
      // add 'selected' prop to the clicked <Button>?
    }

    render() {
        return(
            <ButtonsRow>
                <Button onClick={this.handleClick}>People</Button>
                <Button onClick={this.handleClick}>Members</Button>
                <Button onClick={this.handleClick}>Games</Button>
            </ButtonsRow>  
        );
    }
}

export default ButtonsContainer;

如果单击按钮,我想我想给它 'selected' 属性。这样,如果它有道具,那么它将填充背景颜色。如果没有它,那么它就没有背景颜色。我想也许我可以使用状态来做到这一点,但如果我要那样做,我认为它会应用于每个按钮。感谢您的帮助。

您需要管理每个 Button 的状态。

所有解决方案在"how"您管理按钮状态(作为单个object/array/etc...)时会有所不同,主要概念是获取按钮的id以便知道你指的是哪个状态。

在下一个简单示例中,我使用柯里化函数来提供按钮 id

另一个简单的解决方案是将 id 属性传递给您的按钮并在单击按钮时查询它。

const ButtonsRow = styled.div`
  display: flex;
  justify-content: space-evenly;
`;

const Button = styled.div`
  cursor: pointer;
  :hover {
    background-color: gray;
  }

  background-color: ${props => (props.selected ? 'red' : 'none')};
`;

class ButtonsContainer extends React.Component {
  state = {
    first: false,
    second: false,
    third: true
  };

  toggle = buttonName => () => {
    this.setState(prev => ({ [buttonName]: !prev[buttonName] }));
  };

  render() {
    const { first, second, third } = this.state;
    return (
      <ButtonsRow>
        <Button selected={first} onClick={this.toggle('first')}>
          People
        </Button>
        <Button selected={second} onClick={this.toggle('second')}>
          Members
        </Button>
        <Button selected={third} onClick={this.toggle('third')}>
          Games
        </Button>
      </ButtonsRow>
    );
  }
}

您必须创建一个变量来存储每个按钮的状态。一种更简单的方法可能是从数组动态生成按钮并使用它来维护状态。

class ButtonsContainer extends React.Component {
    state = {
       buttons = [{label:"People"},{label:"Members"},{label:"Games"}]
    }

    handleClick = (button) => (e) => {
      this.setState((prevState) => ({
           buttons: prevState.buttons.filter(btn => btn.label !== button.label)
                                .concat({...button,selected:!button.selected})
      })
    }

    render() {
        return(
            <ButtonsRow>
                {this.state.buttons.map(button => (<Button key={button.label} selected={button.selected} onClick={this.handleClick(button)}>{button.label}</Button>))}
            </ButtonsRow>  
        );
    }
}

export default ButtonsContainer;