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

Log*_*ips 2 javascript reactjs styled-components

我目前正在学习如何在 React 中使用样式组件,但在实现这一点时遇到了麻烦。

我有一排按钮(定义为 div)。单击按钮时,我希望它的背景填充某种颜色。所有其他按钮都应保持“未选中”状态。这是我到目前为止所拥有的:

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;
Run Code Online (Sandbox Code Playgroud)

如果单击 I 按钮,我想我想给它“选定”道具。这样,如果它有道具,那么它将填充背景颜色。如果它没有它,那么它就没有背景颜色。我想也许我可以使用 state 来做到这一点,但如果我这样做了,我认为它适用于每个按钮。谢谢你的帮助。

Den*_*ash 5

你需要管理 eachButton的状态。

所有解决方案在您管理按钮状态的“方式”(作为单个对象/数组/等...)方面都会有所不同主要概念是获取按钮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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

编辑 Q-58628628-ButtonToggle