反应:在选择中保存映射



请告诉我如何保存option的选定值,在我select它只保存第一个值(即One(。如何在select中保存所选值?

这是代码(这是final-form(:

export const SelectFilter = props => {
const { onFilterChange, filterOptions } = props;
return (
<Form
render={({ handleSubmit }) => (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="section">Select:</label>
<Field
id="section"
name="section"
component="select"
onChange={e => onFilterChange(e)}
defaultValue={filterOptions.section}
>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</Field>
</div>
</form>
)}
/>
);
};

以下是我通常在 react 中处理所有表单的方式。这将允许它可重用,通过允许您传递提交功能:D 你也可以传递onChange功能,如果这真的是你想要做的

class GalleryFilter extends React.Component {
constructor(props) {
super(props);
this.state = {
currentValue: "one"
};
this.onChange = this.onChange.bind(this);
this.submit = this.submit.bind(this);
}
onChange(e) {
e.preventDefault();
let {
value
} = e.target;
this.setState({
currentValue: value
});
}
submit(e) {
e.preventDefault();
this.props.Submit(this.state.currentValue);
}
render() {
return ( <
form onSubmit = {
this.submit
} >
<
div >
<
label htmlFor = "section" > Select: < /label> <
select id = "section"
name = "section"
component = "select"
onChange = {
this.onChange
}
value = {
this.state.currentValue
} >
<
option value = "one" > One < /option> <
option value = "two" > Two < /option> <
option value = "three" > Three < /option> <
/select> <
/div> <
/form>
);
}
}

这应该以相同的方式工作

export const GalleryFilter = props => {
const { onFilterChange, filterOptions } = props;
var currentSelection = "one";

function onChange(e)
{
e.preventDefault();
let {value} = e.target;
currentSelection = value;
onFilterChange(e);
}
return (
<Form
render={({ handleSubmit }) => (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="section">Select:</label>
<Field
id="section"
name="section"
component="select"
onChange={onChange}
value={currentSelection}
>
<option value="one">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</Field>
</div>
</form>
)}
/>
);
};

你误解了 React Final Form 的意义。看起来您正在尝试跟踪在state中手动选择的值,但这正是 React Final Form 为您所做的。

如果你想查看当前在选择中选择了什么值,你可以在<Form>给出的 prop 中查看values.section

这是一个演示。

相关内容

  • 没有找到相关文章