简体   繁体   English

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

[英]How to change style of styled-component dynamically?

I am currently learning about using styled-components in React, and having trouble with implementing this.我目前正在学习如何在 React 中使用样式化组件,并且在实现它时遇到了麻烦。

I have a row of buttons (defined as divs).我有一排按钮(定义为 div)。 When a button is clicked, I want it's background to fill with a certain color.单击按钮时,我希望它的背景填充某种颜色。 All of the other buttons should stay 'unselected'.所有其他按钮都应保持“未选中”状态。 Here is what I have so far:这是我到目前为止所拥有的:

 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;

If I button is clicked, I think I wanted to give it the 'selected' prop.如果单击按钮,我想我想给它“选定”道具。 That way, if it has the prop, then it will fill the background color.这样,如果它有道具,那么它将填充背景颜色。 If it doesn't have it, then it doesn't have a background color.如果它没有它,那么它就没有背景颜色。 I thought that maybe I could use state to do this, but if I were to do that, I think it would apply to every button.我想也许我可以使用 state 来做到这一点,但如果我这样做,我认为它适用于每个按钮。 Thanks for any help.谢谢你的帮助。

You need to manage every Button 's state.您需要管理每个Button的 state。

All solutions will different in "how" you manage buttons state (as a single object/array/etc...), the main concept is to get the button's id in order to know which state you refer to.所有解决方案在“如何”管理按钮 state(作为单个对象/数组/等......)方面都会有所不同主要概念是获取按钮的id以了解您指的是哪个 state。

In the next simple example, I use a curried function to provide the button id .在下一个简单的示例中,我使用一个 curried function 来提供按钮id

Another simple solution can be with passing the id attribute to your button and querying it on button click.另一个简单的解决方案是将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>
    );
  }
}

编辑 Q-58628628-ButtonToggle

You have to create a variable to store the state of each button.您必须创建一个变量来存储每个按钮的 state。 A simpler approach may be to dynamically generate the buttons from an array and use the same to maintain the state.一种更简单的方法可能是从数组中动态生成按钮并使用它来维护 state。

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;

Just did that example in order for you to understand the implementation working: https://playcode.io/933026/刚刚做了那个例子,以便您了解实现工作: https://playcode.io/933026/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM