reactjs - 在提交表单上,无法获得反应选择值
问题描述
onSubmit(values) {
console.log("i m clicked", values); /// i didn't get form values
here.
}
renderMacros() {
const { handleSubmit } = this.props;
const macrosData = this.props.macros.macros;
const categoryMacrosData = this.props.categoryMacros.category;
console.log("categoryMacrosData", categoryMacrosData);
const { open } = this.state;
if (macrosData) {
return (
<div>
<div className="form-block-5 w-form">
<form
id="macros-form"
name="macros-form"
onSubmit={handleSubmit(this.onSubmit)}
>
<div className="row">
<div className="col-sm-12">
<label>Type</label>
<Field // this works fine
name="category"
options={MACRO_TYPE_CATEGORIES}
placeholder="Type"
component={SelectInput}
set_default="true"
/>
</div>
<div className="col-sm-12">
<Field // this works fine
name="name"
placeholder="Name Ex. Follow-up template"
component={renderField}
type="text"
className="text-fields w-input"
id="macros_name"
/>
</div>
<div className="col-sm-12">
<Field // here is the problem
type="text"
name="categoryId"
options={categoryMacrosData}
placeholder="Search or add category "
component={AsyncMulti}
handleSelect={this.handleSelectChange}
/>
</div>
</div>
<button>Create Macro</button>
</form>
</div>
</div>
);
}
}
我的组件文件:底线是如果我使用 react-select 库的可创建组件,我无法获得选定的值。
components/Multi.js
import React from "react";
import CreatableSelect from "react-select/lib/Creatable";
const MultiSelect = props => {
const { options, handleSelect } = props;
return <CreatableSelect isMulti onChange={handleSelect} options=
{options} />;
};
export default MultiSelect;
我正在使用 react-select 来选择 redux 形式的选项。提交表单后,我无法获取表单提交的值。我正在使用带有 redux 表单的 react-select 库https://react-select.com/creatable 。
解决方案
您没有handleSubmit
正确绑定,也没有使用refs
,因为您没有获得值。
我建议您尝试使用标签中的绑定代码<form>
:
<form
id="macros-form"
name="macros-form"
onSubmit={this.handleSubmit.bind(this)}
>
还传入refs
您的字段标签以获取值:
<Field
name="categoryId"
options={categoryMacrosData}
placeholder="Search or add category "
component={Multi}
handleSelect={this.handleSelectChange}
ref="categoryId"
/>
而不是写onSubmit
函数:
onSubmit(values) {
console.log("i m clicked", values); /// i didn't get form values
here.
}
用这个函数代码替换它:
handleSubmit(event) {
if (this.refs.categoryId !== '') {
event.preventDefault();
console.log('categoryId: ', this.refs.categoryId.value)
}
}
希望对你有帮助!
推荐阅读
- pyqt5 - QDarkStyle - 如何修改小部件属性?
- java - 使用单个侦听器检查多个元素
- python - 根据元素位置从另一列中提取某些元素
- r - 在 R 中重新定义回归分析的数据框
- python - 使用 python easysnmp 捕获异常
- matplotlib-basemap - 靠近北极的python底图
- r - 在 R 中使用 GAMM 混合模型运行 Cox.ph 模型
- css - 在 CSS Grid 中命名列和行
- python - 将数据加载到 pandas 数据帧到 ms sql python
- python - AttributeError:“模块”对象没有属性“SSLContext”