[英]React - How do I use a handleInputChange function to change a state value that is within a state value?
I am currently trying to have an input field that edits a state value that is within a state value.我目前正在尝试使用一个输入字段来编辑 state 值内的 state 值。 The following is a state example
以下是 state 示例
this.state = {
modalDevice: {
deviceName: "text" //this is what I want changed
}
}
And the following is my handle input change function:以下是我的句柄输入更改 function:
handleInputChange = (event) => {
const { value, name } = event.target;
this.setState({
[name]: value,
});
};
And the following is the field where I call it:以下是我称之为的领域:
<TextField
label="Device Name"
value={this.state.modalDevice.deviceName}
name="deviceName"
variant="outlined"
required={true}
className="classes.textField"
style={{ width: 300 }}
onChange={this.handleModalInputChange}
InputLabelProps={{
classes: {
root: classes.cssLabel,
focused: classes.cssFocused,
},
}}
InputProps={{
classes: {
root: classes.cssOutlinedInput,
focused: classes.cssFocused,
notchedOutline: classes.notchedOutline,
input: classes.input,
},
}}
/>
How would I go about doing this?我将如何 go 这样做?
You can use the spread operator to copy across old state info, before then overwriting it with the new stuff too:您可以使用扩展运算符复制旧的 state 信息,然后再用新内容覆盖它:
this.setState({
...this.state,
modalDevice: {
...this.state.modalDevice
[name]: value,
},
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.