问题
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 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
For this , I am using react-multi-toggle for this toggle switch.
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!
For this , I am using react-multi-toggle for this toggle switch.
Can someone help here?
Code sandbox : https://codesandbox.io/s/react-multi-toggle-solution-perfect-wrx1w
回答1:
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);
}
};
来源:https://stackoverflow.com/questions/57592935/dynamically-add-classes-on-based-on-state-value-and-also-change-the-children-con