问题:
我在我的 Formik 表单中选择了输入作为反应。我的代码如下
<select
className="form-control offence-select"
id="exampleFormControlSelect1"
value={props.values.offenceId}
onChange={props.handleChange("offenceId")}
onBlur={props.handleBlur("offenceId")}
>
<option value={0}>Select Offence</option>
{this.renderOption()}
</select>
Run Code Online (Sandbox Code Playgroud)
我想要的是我想在 onChange 中调用两个函数,一个函数是 formik props.handleChange ,下一个是自定义状态更新。
我做了这样的事情。
onChange={e=>{props.handleChange("offenceId");this.handleOffence(props.values.offenceId)}}
Run Code Online (Sandbox Code Playgroud)
但它只调用第二个自定义函数,但不会更改选择的字段值。我尝试了很多来找到解决此问题的方法,但我无法这样做。有人可以通过更正我调用函数的方式来帮助我解决这个问题吗?谢谢你。
小智 8
您也必须传递该事件,否则您的回调不知道新值是什么。我也不会指望props.values立即获得新值,这就是为什么我会在第二个函数调用中传递来自 event 的值。
<select
className="form-control offence-select"
id="exampleFormControlSelect1"
value={props.values.offenceId}
onChange={(e) => {
props.handleChange("offenceId")(e);
this.handleOffence(e.currentTarget.value);
}}
onBlur={props.handleBlur("offenceId")}
>
<option value={0}>Select Offence</option>
{this.renderOption()}
</select>
Run Code Online (Sandbox Code Playgroud)
您还可以为您的选择输入命名如下,这简化了回调调用:
<select
name="offenceId"
className="form-control offence-select"
id="exampleFormControlSelect1"
value={props.values.offenceId}
onChange={(e) => {
props.handleChange(e);
this.handleOffence(e.currentTarget.value);
}}
onBlur={props.handleBlur}
>
<option value={0}>Select Offence</option>
{this.renderOption()}
</select>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2746 次 |
| 最近记录: |