У меня есть компонент, который получает json список вопросов из API. Затем для каждого вопроса есть 5 переключателей (от «категорически не согласен» до «полностью согласен»).
Вопросы выбираются в componentDidMount (), хранятся в this.state.questions и сопоставляются с questionComponents в рендере (). Компоненты (и переключатели) идентифицируются по ключу.
Мне нужно хранить ответы в виде массива в состоянии. Очевидно, это должно происходить в handleChange, но я не знаю, как это сделать. Я довольно новичок, чтобы реагировать, поэтому, вероятно, есть более простой способ сделать это, чем то, что я делаю сейчас.
Вот приложение. js
import React from 'react';
import Question from './Question';
class App extends React.Component {
constructor() {
super()
this.state = {
questions: [],
answers: []
}
this.handleChange = this.handleChange.bind(this)
}
handleChange(event) {
const {name, value, type, checked, key} = event.target
this.setState(prevState => {
//
}
}
componentDidMount() {
fetch("http://localhost:7777/api/questions")
.then(response => response.json())
.then(data => {
this.setState({
questions: data
})
})
}
render () {
const questionComponents = this.state.questions.map(question =>
<Question key={question.id} question={question.question} handleChange = {this.handleChange} />)
return (
<div>
<h1> Questions!</h1>
{questionComponents}
</div>
)
}
}
export default App;
И Вопрос. js
import React from "react"
function Question(props) {
return (
<div className="question">
<p>{props.question}</p>
<label>strongly disagree</label>
<input
type="radio"
name={props.key}
key={props.key}
value="1"
onChange={props.handleChange}>
</input>
<label> disagree</label>
<input
type="radio"
name={props.key}
key={props.key}
value="2"
onChange={props.handleChange}>
</input>
<label>no opinion</label>
<input
type="radio"
name={props.key}
key={props.key}
value="3"
onChange={props.handleChange}>
</input>
<label> agree</label>
<input
type="radio"
name={props.key}
key={props.key}
value="4"
onChange={props.handleChange}>
</input>
<label>strongly agree</label>
<input
type="radio"
name={props.key}
key={props.key}
value="5"
onChange={props.handleChange}>
</input>
</div>
)
}
export default Question