【发布时间】:2017-12-15 00:02:24
【问题描述】:
我有一个具有多个键的状态对象(“汽车”),其中一个是数组(“特征”)。我正在尝试用它做几件事。
- 每次单击“添加功能”按钮时,我都想将另一个字符串(另一个功能)推送到“功能”数组中。
- 当我输入相应的输入时,我希望能够更新“功能”数组中每个字符串/功能的状态。
我在网上对此进行了相当多的研究,但没有发现任何东西(可能是因为这不可能)。无论哪种方式,这是我的代码:
class Car extends React.Component {
state = {
car: {make: 'Toyota', model: 'Camry', features: []},
}
handleChange = (e, index) => {
const value = e.target.value
let features = this.state.car.features.slice() // create mutable copy of array
features = features[index].concat(value)
this.setState({...this.state.car, features: features})
}
handleAddFeature = () => {
let features = this.state.car.features.slice()
features.push('')
this.setState({...this.state.car, features: features})
}
render() {
return (
{
this.state.car.features.map((f, index) => { return <input key={index} onChange={e => this.handleChange(e, index)}>{feature}</input>
}
<button onClick={this.handleAddFeature}>Add Feature</button>
)
}
}
【问题讨论】:
-
你能举个例子“当我输入相应的输入时,我希望能够更新“特征”数组中每个字符串/特征的状态?”
标签: javascript arrays reactjs state