在React JS中,我试图创建一个函数,该函数使用输入的值更新输入字段的onChange事件的状态。
状态模型必须保持这样,因为我必须这样发布它(以匹配API结构等)。
但是我不知道如何获取每条记录的状态“答案”部分。
// State --------------------------------------
state = {
values: [
//1
{
section: "a",
answers:
{
1a: 1,
1b: 2,
1c: 3,
1d: 4,
1e: 5
}
},
//2
{
section: "b",
answers:
{
2a: 1,
2b: 2,
2c: 3,
2d: 4,
2e: 5,
2f: 6,
2g: 7,
2h: 7
}
}
]
}
// Set value ----------------------------------
setValue = (key, val) => {
this.setState((state) => ({
values: {
...state.values,
[key]: val
}
}));
};
// Handle input change ------------------------
handleChange = key => e => {
this.setValue(key, e.target.value)
};
//Usage ---------------------------------------
<input
id="input1"
type="number"
onChange={handleChange(values.1a)}
defaultValue={values.1a}
/>
<input
id="input2"
type="number"
onChange={handleChange(values.2c)}
defaultValue={values.2c}
/>
答案 0 :(得分:1)
您可以尝试以下代码:
// Example class component
class Thingy extends React.Component {
constructor(props) {
super(props)
this.state = {
values: [
//1
{
section: "a",
answers:
{
a1:1,
b1:2,
c1:3,
d1:4,
e1:5
}
},
//2
{
section: "b",
answers:
{
a2:1,
b2:2,
c2:3,
d2:4,
e2:5,
f2:6,
g2:7,
h2:7
}
}
]
}
}
setValue = (Key, val) => {
let output = this.state.values.map(value=>{
if (Key in value.answers)
{
let tempValue = {
...value,
answers:
{
...value.answers,
[Key] : Number(val)
}
}
return tempValue
}
else
{
return value
}
})
this.setState({
values:output
})
};
handleChange =(e, key) => {
this.setValue(key, e.target.value)
}
getDefaultValue=(Key)=>{
let output
this.state.values.forEach(value=>{
if (Key in value.answers)
{
output = value.answers[Key]
}
})
return output
}
render() {
return (
<div>
<input id="input1" type="number" onChange={(e)=>this.handleChange(e,"a1")} value={this.getDefaultValue("a1")} />
<input id="input2" type="number" onChange={(e)=>this.handleChange(e,"c2")} value={this.getDefaultValue("c2")} />
</div>
)
}
}
// Render it
ReactDOM.render(
<Thingy title="I'm the thingy" />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>