根据状态和索引动态更改样式组件

Dynamically change styled component based on state AND index

所以我有一个从 API 请求返回的列表(不重要) 让我们称之为 list = [1,2,3,4,5,6,7];

现在,在 render() 中,我有如下内容

render(){
  <Wrapper>
    {list.map((i) => {
      return (<Button id = {i} onClick = {this.customFunc.bind(this, i)} />)
    }
  </Wrapper>
}

现在,我有另一个列表,我们称它为 list_check = [false...](对于上面列出的所有 7 个元素)

假设 customFunclist_check 中的相应按钮 ID 从 false 更改为 true。

例如如果我点击按钮 1 (id = 1) 然后 list_check 变成 [false, true, false...]

** 现在我的问题是:我有 2 个样式组件,ButtonButton_Selected, 我如何在 2 个样式组件之间动态更改,以便如果单击该唯一按钮(更改 list_check[index] = true),元素变为 Button_Selected 而不是 Button(整个列表初始化为 Button 因为所有元素都是 false)

澄清一下: 两个数组都位于 this.state 中,通过 2 个样式组件我的意思是存在

const Button = styled.div`
  //styling here
`;

const Button_Selected = Button.extend`
 //Small styling change to differentiate between selected and not selected
`;

编辑:所有答案都很棒!可惜我只能select一个:(

尽管您可以 return 2 个基于条件渲染的按钮。您也可以将 props 传递给 styled Button,这样您就可以根据 props 更改样式。

   render(){
  <Wrapper>
    {list.map((i) => {
      return (<Button id = {i} isSelected={this.state.list_check[i]} onClick = {this.customFunc.bind(this, i)} />)
    }
  </Wrapper>
}

在您的样式按钮中:

  const Button = styled.div`
  styleName: ${props => props.isSelected ? 'styling_if_Selected' : 'styling_if_not_selected'};
`;

您可以将组件保存到另一个变量。

this.state.list_check.map((item, i) => {
    const NecessaryButton = item ? SelectedButton : Button;
    return <NecessaryButton onClick={() => this.makeSelected(i)}>Normal Button</NecessaryButton>
})

你可以看到一个活生生的例子here

最简单的方法是拥有一个 Button 组件并在其被选中时处理该状态。根据此状态,您可以切换 类。 示例:

class Button extends React.Component {
    state = {
        isSelected: false
    };

    handleClick() {
        //Here we will set the state change and call the onClick function passed by props
        this.setState({isSelected: !this.state.isSelected}, () => { this.props.onClick(); });
    }

    render() {
        return (
            <button 
                class={this.state.isButtonSelected ? "classBtnSelected" : "classBtnDefault"} 
                onClick={this.handleClick}
            />
        );
    }
}

不过,如果你想切换组件,你可以使用状态来控制它是否被选中并进行条件渲染。示例:

render(){
  <Wrapper>
    {list.map((i) => {
      return (this.state.isSelected 
         ? <Button id={i} onClick = {this.customFunc.bind(this, i)} /> 
         : <Button_Selected id={i} onClick = {this.customFunc.bind(this, i)} />)
    }
  </Wrapper>
}