【发布时间】:2020-08-14 21:20:46
【问题描述】:
我有一个从 api 获取问题的 json 列表的组件。然后每个问题都有 5 个单选按钮供您回答(从“非常不同意”到“非常同意”)。
问题在 componentDidMount() 中获取,存储在 this.state.questions 中,并在 render() 中映射到 questionComponents。组件(和单选按钮)由键标识。
我需要将答案作为数组存储在状态中。这显然必须在handleChange中发生,但我不知道如何做到这一点。我对反应很陌生,所以可能有比我现在做的更简单的方法。
这里是 App.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;
还有 Question.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
【问题讨论】:
-
你能提供一个示例json吗?服务器的线路可能是本地的..
-
``` [ { "id": 48, "question": "这是一个示例问题吗?" }, { "id": 50, "question": "这个怎么样?" }, ``` 在我发布问题后,我实际上明白了这一点。我的问题是我试图使用 key 属性来识别问题,而实际上我必须将 id 发送到问题组件并将其用作名称,之后很容易从 event.target.name 和保存状态
标签: javascript reactjs forms radio-button