有两个问卷列表卡,其中的每一个具有一questionnaire_id和几个question_choice_id,在选择了单选按钮时,它可以基于quisioner_id,如何添加quisioner_id只选择一个question_choice_id 和question_choice_id进入react hooks的状态?
所以这个假设就是这样
choice_id: [1,1], question_id: [2,4]
handleSelected函数
const handleSelected = (choiceId, questionId) => {
setQuestion(questionId)
setChoice(choiceId)
console.log(questionId, choiceId)
}
handleSubmit函数
const handleSubmit = (e) => {
const choice_id = choiceId
const question_id = questionId
const quisioner = {
choice_id,
question_id
}
e.preventDefault()
api.post('api/questionnaire/response', quisioner, { headers: { 'Authorization': JSON.parse(storage.getItem('token')) } })
.then(res => {
console.log(res)
})
}
这是单选按钮
<Form className='w-100' onSubmit={handleSubmit}>
<Row>
{listQuisioner.map((item) => {
return (
<Col key={item.question_id} md={6} xs={12} className='mb-3'>
<Card>
<Card.Body style={{ position: 'relative' }}>
<h4 className='text-capitalize'>{item.question}</h4>
<div className='navbar-top-line mb-4'/>
{item.question_choice.map(res => {
return (
<fieldset key={res.choice_id} id={res.choice_id}>
<label className='text-capitalize'>{res.choice}</label>
<input
type='radio'
id={res.choice_id}
value={res.choice_id}
name={res.choice}
checked={res.choice_id ? selected : null }
onChange={() => handleSelected(res.choice_id, item.question_id)}
/>
</fieldset>
)
})}
</Card.Body>
</Card>
</Col>
)
})}
<Col xs={12} className='p-3 mb-5'>
<Button variant='danger' block type='submit'>
<h5 className='mb-0'>Submit</h5>
</Button>
</Col>
</Row>
</Form>
答案 0 :(得分:0)
您可以使用React的useState()挂钩将quisionerId,questionChoiceId保持在状态。
[quisionerId,setQuisionerId] = React.useState("");
[questionChoiceId,setQuestionChoiceId] =React.useState("");
//On handle selected
const handleSelected = (choiceId, questionId) => {
setQuisionerId({choice_id : choiceId, question_id : questionId);
setQuestionChoiceId(choiceId)
}