我正在尝试学习如何在提交表单后重置选项。我不确定如何完成这项任务。任何建议将不胜感激!
import '../App.css'
import React, { useState } from 'react';
function Interface() {
const [choices, setChoices] = useState({
selectValue: 'Pick Reason',
damageValue: 'Pick Reason',
submitted: false,
default: 'Pick Option',
})
let handleCart = function(e){
return setChoices({...choices,selectValue: e.target.value})
}
let handleDamage = function(e){
return setChoices({...choices,damageValue: e.target.value})
}
let buttonSub = function(e){
e.preventDefault()
alert(`your teacher is ${choices.selectValue} your damage is ${choices.damageValue}`)
setChoices({selectValue: '', damageValue: '', submitted: !true})
}
return (
<div className="App">
<h1>Chromebook Deposit Form</h1>
<form>
<div className="form-group">
<label>Select Whose Cart your chromebook belongs too</label>
<select className="form-control w-50 " id="cart" onChange={handleCart} placeholder='hi'>
<option>{choices.default}</option>
<option>Emily Freitag</option>
<option>Santoro</option>
<option>Warner</option>
<option>Baltzell</option>
</select>
<hr></hr>
<label>Select Your Reason For deposit</label>
<select className="form-control w-50 " id="cart" onChange={handleDamage}>
<option>{choices.default}</option>
<option>Broken Screen</option>
<option>Broken Keys</option>
<option>Broken Case</option>
<option>Other</option>
</select>
<button className="button" onClick={buttonSub}>Submit Information</button>
</div>
</form>
</div>
);
}
export default Interface;
我尝试动态设置有效的值,但我无法弄清楚如何在提交表单后使其显示某个值。
您没有完全控制您的输入。您提供的是更改处理程序,而不是值。尝试简单地向选择添加一个值:
<select
className="form-control w-50 "
id="cart"
value={choices.selectValue}
onChange={handleCart}
placeholder='hi'
>
...
<select
className="form-control w-50 "
id="cart"
value={choices.damageValue}
onChange={handleDamage}
>
然后在提交时,您可以将选择的状态值更新为您希望它们重置的状态值(看起来您已经是(。
但是,除非 react 自动处理这个问题并且我不知道,否则您还需要设置每个选项的值。在这种情况下,标签的字符串就足够了:
<select
className="form-control w-50 "
id="cart"
value={choices.damageValue}
onChange={handleDamage}
>
<option value={'default'}>{choices.default}</option>
<option value={'Broken Screen'}>Broken Screen</option>
<option value={'Broken Keys'}>Broken Keys</option>
<option value={'Broken Case'}>Broken Case</option>
<option value={'Other'}>Other</option>
</select>
另外:这个submitted: !true
似乎没有必要。只需使用false
,除非!
是错别字。