【问题标题】:changing style object at index of array in state in react在反应中更改状态数组索引处的样式对象
【发布时间】:2020-03-12 13:43:35
【问题描述】:

当使用 toggleSelected () 在另一个组件中单击选项时,我正在尝试更新我的应用程序状态中的选项数组中的样式对象。有谁知道如何最好地访问对象并将背景颜色设置为不同的颜色?

App.js

this.state = {
    options: [
      {
        id: 0,
        label: "Industrial Truck and Tractor Operators",
        value: "53-7051",
        style: {
          display: "flex",
          margin: "auto",
          paddingTop: "1em",
          paddingBottom: "1em",
          paddingLeft: "1em",
          borderBottom: "solid",
          borderColor: "black",
          borderWidth: ".1em",
          color: "#64bd9a",
          backgroundColor: "white"
        },
        tooltip_text:
          'Operate industrial trucks or tractors equipped to move materials around a warehouse, storage yard, factory, construction site, or similar location. Excludes “Logging Equipment Operators" (45-4022).'
      },
      {
        id: 1,
        label: "Order Clerks",
        value: "43-4151",
        style: {
          display: "flex",
          margin: "auto",
          paddingTop: "1em",
          paddingBottom: "1em",
          paddingLeft: "1em",
          borderBottom: "solid",
          borderColor: "black",
          borderWidth: ".1em",
          color: "#64bd9a",
          backgroundColor: "white"
        },
        tooltip_text:
          'Receive and process incoming orders for materials, merchandise, classified ads, or services such as repairs, installations, or rental of facilities. Generally receives orders via mail, phone, fax, or other electronic means. Duties include informing customers of receipt, prices, shipping dates, and delays; preparing contracts; and handling complaints. Excludes "Dispatchers, Except Police, Fire, and Ambulance" (43-5032) who both dispatch and take orders for services.'
      }
    ],
    value: null,
    styles: {
      //container style is working
      marginTop: "2em",
      marginLeft: "2em",
      borderStyle: "solid",
      borderWidth: ".1em",
      borderBottom: "none",
      borderRight: "solid",
      width: "19em",
      textAlign: "justify",
      backgroundColor: "white",
      boxShadow: "3px 6px 5px #9E9E9E"
    },
    className: "",
    selectedClassName: "",
    loading_State: true, //this changes to false when the component loads
    childrenCount: 0
  };

  toggleSelected = child => {
    this.setProps({options.indexOf('1').style.backgroundColor: "gray" })
  };

组件.js

render() {
    return (
      <div style={this.props.styles}>
        {this.props.options.map(option => (
          <div
            key={option}
            id={"option" + option.id}
            style={option.style}
            onClick={e => {
              if (this.props.setProps) {
                this.props.setProps({ value: e.target.value });
              } else {
                this.setState({ value: e.target.value });
              }
              this.props.toggleSelected(option.id); //passing my index here to the function
            }}
          >
            <span id={option.id}> {option.label} </span>
            <UncontrolledTooltip
              placement="right"
              target={"option" + option.id}
            >
              {option.tooltip_text}
            </UncontrolledTooltip>
          </div>
        ))}
      </div>
    );
  }

在此处更新样式对象方面,我是否以正确的方式进行此操作。我应该使用不同的方法。我也想在不使用 CSS 的情况下执行此操作,因此添加 classNames 不是我想要做的。

【问题讨论】:

  • setProps 是做什么的。我认为您可能需要重新考虑应用程序流程。实现一件相当简单的事情有点复杂。

标签: reactjs styles state


【解决方案1】:

我相信以下应该可以工作,假设这里的childIndex 代表您要修改的state.options 数组的索引。

toggleSelected = (childIndex) => {
  const newOptions = this.state.options.map((option, i) => {
    if (i !== childIndex) {
      return option;
    }
    return {
      ...option,
      style: {
        ...option.style,
        backgroundColor: "green" // your color here
      }
    }
  });

  this.setState({ options: newOptions });
}

编辑:如果您需要将所有其他颜色更改为白色,您可以执行以下操作:

toggleSelected = (childIndex) => {
  const newOptions = this.state.options.map((option, i) => {
    return {
      ...option,
      style: {
        ...option.style,
        backgroundColor: i === childIndex ? "green" : "white"
      }
    }
  });

  this.setState({ options: newOptions });
}

【讨论】:

  • 感谢您的回答,这很有效,而且很容易理解:),我唯一的问题是我只想更新其中一个选项的样式,而不是全部。您能否以最合理的方式进行编辑以实现此目的?
  • 这应该只更新与提供的childIndex 对应的选项。这不是它的工作方式吗?
  • 嗨,我可以使用它,现在它可以完美运行,我不确定我在那里做错了什么。再次感谢您!
  • 嘿,我知道这是一个额外的唠叨问题,但我也希望问我如何仅将选定的颜色背景更改为“绿色”,同时更改所有非选择“白色”选项?
  • 我实现了您的解决方案并且它有效。我唯一改变的是我在三元运算符中使用了 childIndex.id :) 谢谢!
猜你喜欢
  • 2019-05-17
  • 2018-03-21
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 2017-08-08
  • 1970-01-01
相关资源
最近更新 更多