javascript 如何使用formik react js在handlesubmit函数中接收选择值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50343914/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to receive select value in handlesubmit function with formik react js?
提问by Ahmad
i am developing a form in reactjs using formik plugin plugin link. when i submit form i am getting text fields values but dropdown values are coming empty...
我正在使用 formik 插件插件链接在 reactjs 中开发一个表单。当我提交表单时,我得到了文本字段值,但下拉值变为空...
this is my dropdown select
这是我的下拉选择
<div className="form-group">
<Field component="select" id="category" name="category" value={this.state.value} className={"form-control"} onChange={ this.handleChange }>
<option value="lokaler">Lokaler</option>
<option value="jobb">Jobb</option>
<option value="saker-ting">Saker & ting</option>
<option value="evenemang">Evenemang</option>
</Field>
</div>
handle submit function
处理提交功能
export default withFormik({
enableReinitialize: true,
mapPropsToValues({ category }) {
return {
category: category || ''
}
},
handleSubmit(values, { setStatus, setErrors }){
console.log("data is this: ");
console.log(values); //here i am getting all form fields values except select value returning empty value
console.log("category: "+values.category);// here i always get empty value but not getting selected value
}
i am getting all text fields values in handle submit function but i am not able to get dropdown selected value....kindly tell me how to get dropdown select value in handle submit function ?
我正在获取句柄提交功能中的所有文本字段值,但我无法获得下拉选择值......请告诉我如何在句柄提交功能中获取下拉选择值?
回答by Tun Tun Aung
I also faced this problem yesterday. My problem was to submit form that contains ant design dropdown. I finally make it work after hours of:
我昨天也遇到了这个问题。我的问题是提交包含蚂蚁设计下拉菜单的表单。经过几个小时的努力,我终于让它工作了:
- revisiting the Formik Docs
- watch Andrew Mead's video Better React Form with Formikagain.
- also viewing Jared Palmer's Working with 3rd-party inputs #1: react-select
- 重温Formik 文档
- 再次观看 Andrew Mead 的视频Better React Form with Formik。
- 还查看 Jared Palmer 的使用 3rd-party 输入 #1:react-select
The doc said you need to set onChange, onBlurevents to setFieldValue, setFieldTouchedprops respectively like 3rd-party input example:
该文档说您需要将onChange、onBlur事件分别设置为setFieldValue、setFieldTouched道具,如第 3 方输入示例:
<MySelect
value={values.topics}
onChange={setFieldValue}
onBlur={setFieldTouched}
error={errors.topics}
touched={touched.topics}
/>
So to my problem, I need to change a bit:
所以对于我的问题,我需要稍微改变一下:
<Select
{...field}
onChange={(value) => setFieldValue('fruitName', value)}
onBlur={()=> setFieldTouched('fruitName', true)}
value={values.fruitName}
...
>
...
</Select>
Hope this will help.
希望这会有所帮助。
Here is my CodeSandbox
这是我的CodeSandbox
回答by Faktor 10
A more robust way to handle select components whilst using Formik would be to also use Jed Watsons react-selectcomponent. The two work together nicely and abstract away a lot of the boilerplate you would normally need to implement to get the component working seamlessly with Formik.
在使用 Formik 时处理选择组件的更健壮的方法是还使用 Jed Watsons react-select组件。两者很好地协同工作,并抽象出许多您通常需要实现的样板,以使组件与 Formik 无缝协作。
I have forked a simple example from Jared Palmer's react-select / Formik exampleon codesandbox and adjusted it to reflect your code above.
我已经从Jared Palmer在 codeandbox 上的 react-select / Formik 示例中创建了一个简单的示例,并对其进行了调整以反映您上面的代码。
import "./formik-demo.css";
import React from "react";
import { render } from "react-dom";
import { withFormik } from "formik";
import Select from "react-select";
import "react-select/dist/react-select.css";
const options = [
{ value: "lokaler", label: "Lokaler" },
{ value: "jobb", label: "Jobb" },
{ value: "saker-ting", label: "Saker & ting" },
{ value: "evenemang", label: "Evenemang" }
];
const MyForm = props => {
const {
values,
handleChange,
handleBlur,
handleSubmit,
setFieldValue
} = props;
return (
<form onSubmit={handleSubmit}>
<label htmlFor="myText" style={{ display: "block" }}>
My Text Field
</label>
<input
id="myText"
placeholder="Enter some text"
value={values.myText}
onChange={handleChange}
onBlur={handleBlur}
/>
<MySelect value={values.option} onChange={setFieldValue} />
<button type="submit">Submit</button>
</form>
);
};
class MySelect extends React.Component {
handleChange = value => {
// this is going to call setFieldValue and manually update values.topcis
this.props.onChange("option", value);
};
render() {
return (
<div style={{ margin: "1rem 0" }}>
<label htmlFor="color">Select an Option </label>
<Select
id="color"
options={options}
onChange={this.handleChange}
value={this.props.value}
/>
</div>
);
}
}
const MyEnhancedForm = withFormik({
mapPropsToValues: props => ({
myText: "",
option: {}
}),
handleSubmit: (values, { setSubmitting }) => {
console.log(values);
}
})(MyForm);
const App = () => <MyEnhancedForm />;
render(<App />, document.getElementById("root"));
There are a few gotchas, you have to include the react select css for the component to display properly
有一些问题,您必须包含 react select css 才能使组件正确显示
import "react-select/dist/react-select.css";
the function mapPropsToValues option field should be initialised to an object
函数 mapPropsToValues 选项字段应该初始化为一个对象
mapPropsToValues: props => ({
myText: "",
option: {}
Finally here is a link to the codesandbox example
最后这里是代码和框示例的链接


