javascript - React Select 值未在状态更改时重置
问题描述
我有一个选择组件需要在用户单击下一步按钮后重置为“中性”状态。然而,它只是继续显示用户之前选择的内容。我将它们拆分为如下所述的组件。您可以看到按下下一个按钮时,defaultValue 重置为“3”,但这似乎仅适用于组件首次呈现时,并且在随后的按下时不再适用。
const QuestionLikert = ({ nextQuestion, prevQuestion, setLikertResponse, likertResponse }) => {
return (
<div className='section'>
<div className='container'>
<div>
<div>
<select
id='response'
name='response'
onChange={setLikertResponse}
defaultValue={likertResponse}
>
<option value="1">Strongly Disagree</option>
<option value="2">Disagree</option>
<option value="3">Neutral</option>
<option value="4">Agree</option>
<option value="5">Strongly Agree</option>
</select>
</div>
<button onClick={nextQuestion}>
Next
</button>
<div>
<span onClick={prevQuestion}>Back </span>
</div>
</div>
</div>
</div>
)}
const ParentComponent = () => {
const [currentQuestion, setCurrentQuestion] = useState(0)
const [likertResponse, setLikertReponse] = useState('3')
const handleLikertInput = (e) => {
setLikertReponse(e.target.value)
}
const toggleNextQuestion = () => {
setLikertReponse('3')
setCurrentQuestion(currentQuestion + 1)
}
const togglePrevQuestion = () => {
setCurrentQuestion(currentQuestion - 1)
}
return (
<Layout>
<div className='section'>
<div className='container'>
<div>
<QuestionLikert
nextQuestion={toggleNextQuestion}
prevQuestion={togglePrevQuestion}
setLikertResponse={handleLikertInput}
likertResponse={likertResponse}
/>
</div>
</div>
</div>
</Layout>
)
}
解决方案
的<select>
值参数QuestionLikert
应该由likertResponse
道具控制,因为它的状态来自ParentComponent
<select
id='response'
name='response'
onChange={setLikertResponse}
value={likertResponse}
>
<option value="1">Strongly Disagree</option>
<option value="2">Disagree</option>
<option value="3">Neutral</option>
<option value="4">Agree</option>
<option value="5">Strongly Agree</option>
</select>
推荐阅读
- c++ - “gpu/mxGPUArray.h”文件的路径在哪里?
- android - 底部导航未固定到片段视图内的底部
- c++ - 为什么这段代码没有使用 `-Wlifetime` 触发警告?
- f# - 在 F# 中,如何更新可选的嵌套记录?
- database - 3NF归一化和分解
- mongodb - MongoDB compass 创建 SSH 隧道时出错:所有配置的身份验证方法均失败
- windows - 游戏中 NPC 的机器学习:Windows ML 还是 DirectML?
- reactjs - 使用startAfter时按降序排列的firestore顺序
- c# - 具有依赖关系的 Windows 服务的关闭顺序
- haskell - 制作保护功能时,在 Haskell 中收到“变量不在范围内”错误