根据状态值动态添加 类 并根据 parent 的状态变化更改 children 内容

Dynamically add classes on based on state value and also change the children content based on parent's state change

我正在为一个应用程序实现一个设置页面。对于每个设置,我都实现了一个启用(绿色)或禁用(红色)状态的滑块。但是 parent 的设置是只读的,是根据其 children.

的值计算的

Parent也应该是可变的; Parent 绿色应将所有 children 变为绿色;在红色上它应该是红色的;但待定它应该保持原样

为此,我使用 react-multi-toggle 作为此切换开关。

此外,如果我想根据所选状态动态添加背景颜色,我该怎么做。根据 react-multi-toggle 文档知道 optionClass 被添加到选定的选项。现在我想要选择的颜色作为整个容器的颜色。有一个名为 "className" 的选项购买 class 名称不会被附加!

为此,我使用 react-multi-toggle 作为此切换开关。

有人可以帮忙吗?

代码沙箱:https://codesandbox.io/s/react-multi-toggle-solution-perfect-wrx1w

您可以在 Setting Component 上添加父状态更改时切换子状态。 查看完整 working sandbox here。主要变化是

  // This function minght not be needed, if your few child switches
  // Just adding it in case you have multiple children
  setChildrenValue = value => {
    // state is immutable, we need clone it.
    const clonedState = JSON.parse(JSON.stringify(this.state));
    for (let key in clonedState) {
      clonedState[key] = value;
    }

    this.setState(
      prevState => ({ ...prevState, ...clonedState }),
      this.handleChange
    );

    /**
         * Use this if your few children and remove code above
         * 
          this.setState(prevState => ({
            ...prevState,
            parentVal: value,
            switch1Val: value,
            switch2Val: value
          }), this.handleChange);
        */
  };

handleParentClick = parentVal => {
  if (parentVal === "pending") {
    this.setState(
      prevState => ({ ...prevState, parentVal }),
      this.handleChange
    );
  } else {
    this.setChildrenValue(parentVal);
  }
};