상태 ("car")에 여러 개의 키가있는 객체가 있는데 그 중 하나가 배열 ("features")입니다. 내가하고 싶은 일이 몇 가지 있습니다.객체 내부에 중첩 된 배열의 상태 업데이트 (ReactJS)
- "기능 추가"버튼을 클릭 할 때마다 "기능"배열에 다른 문자열 (다른 기능)을 추가하려고합니다.
- 각 입력에 입력 할 때 "features"배열의 각 문자열/기능의 상태를 업데이트 할 수 있기를 원합니다.
나는이 온라인을 상당히 연구했으며 아무 것도 발견하지 못했습니다 (어쩌면 불가능하기 때문에).
handleAddFeature =() => {
const car = this.state.car
car.features.push('Your feature')
this.setState({ car })
}
그냥 복사본을 생성하고 자동차의 새로운 가치에 밀어
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>
)
}
}
"각 입력을 입력 할 때"features "배열의 각 문자열/기능의 상태를 업데이트 할 수 있습니까? – adrice727