根据状态值动态添加类,并根据父状态变化更改子内容 [英] Dynamically add classes on based on state value and also change the children content based on parent's state change

查看:56
本文介绍了根据状态值动态添加类,并根据父状态变化更改子内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am implementing a setting page for an application. For each setting I have implemented a slider that has enabled(green) or disabled(red) state. But parent's settings is read only and is calculated based on the values of its children.

Parent 也应该是可变的;绿色的父母应该将所有孩子都变成绿色;在红色它应该是红色的;但待定它应该保持原样

Parent should also be changeable ; Parent on green should turn all children to green ; On red it should be red ; But pending it should be as is

为此,我为此切换开关使用了 react-multi-toggle.

For this , I am using react-multi-toggle for this toggle switch.

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

Also If I want to dynamically add background color based on the state selected, how do I go about it. According to react-multi-toggle documentation know optionClass gets added to selected option. Now i want the selected color as the color for the entire container.. There's an option called "className" buy the class name doesn't get appended!

为此,我为此切换开关使用了 react-multi-toggle.

For this , I am using react-multi-toggle for this toggle switch.

有人可以帮忙吗?

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

推荐答案

您可以在 Setting Component 上添加当父状态更改时切换子状态.在此处查看完整的工作沙箱.主要变化是

You can add toggle children state when parent state change on the Setting Component. Check out full working sandbox here. Key changes are

  // 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);
  }
};

这篇关于根据状态值动态添加类,并根据父状态变化更改子内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆