我如何动态地选择一个状态属性对象名称来改变它的一个属性(子属性?)



我有这样一个类的状态属性。

state = {
step: 1,
clientName: '',
icecreamFlavors: {
vanilla: false,
chocolate: false,
mintChocolateChip: false
},
toppings: {
sprinkles: false,
caramel: false,
whippedCream: false
someOtherProperty1: '',
someOtherProperty2: ''
};

不需要全部阅读的简短版问题:怎样才能使这句话的最后部分"充满活力"呢?所以改变:this.state.icecreamFlavorsthis.state.<variable-here>


这个属性是从由两种类型的字段、文本和复选框组成的html表单更新的。我使用这个方法来更新文本属性。

handleChange = (input: any) => (e: { target: { value: any } }) => {
this.setState({ [property]: e.target.value });
};

对于复选框,我使用了另一种方法,只适用于"icecreamFlavors"这就是我想要修复的(因为我想创建一个通用方法,而不是为每个带子属性重复相同的方法):

handleCheckboxChange = (parentProperty: any, property: any) => (e: { target: { checked: any} }) => {
this.setState({[parentProperty]: {...this.state.icecreamFlavors, [property]: e.target.checked} })
};

这是预期的工作,让我更新"icecreamFlavors",但我想让"handleCheckboxChange"通用到可以与任何其他属性(例如:topings)一起使用。

html字段看起来像这样(为了简单起见,只提取了复选框):

<input
type="checkbox"
name="vanilla"
onChange={handleCheckboxChange('icecreamFlavors','vanilla')}
/>
<br />
<input
type="checkbox"
name:"chocolate"
onChange={handleCheckboxChange('icecreamFlavors','chocolate')}
/>
<br />
<input
type="checkbox"
name:"mintChocolateChip"
onChange={handleCheckboxChange('icecreamFlavors','mintChocolateChip')}
/>
<br />
<input
type="checkbox"
name:"sprinkles"
onChange={handleCheckboxChange('toppings','sprinkles')}
/>
<br />
<input
type="checkbox"
name:"caramel"
onChange={handleCheckboxChange('toppings','caramel')}
/>  

我想实现的是改变"handleCheckboxChange"方法执行如下操作(此代码不运行…)

handleCheckboxChange = (parentProperty: any, property: any) => (e: { target: { checked: any} }) => {
this.setState({[parentProperty]: {...this.state.parentProperty, [property]: e.target.checked} })
};

使...this.state.icecreamFlavors...this.state.parentProperty一样动态

我已经做了一些尝试,如this.setState({[parentProperty]: {...[parentProperty], [property]: e.target.checked} })this.setState({[parentProperty]: {parentProperty, [input]: e.target.checked} }),但我的尝试没有给我我想要的结果。

如果需要更多的上下文或信息,请告诉我。

提前感谢!!

你可以试试这个吗

const newObj = this.state[parentProperty];
newObj[input] = e.target.checked;
this.setState({[parentProperty]: newObj});

最新更新