我正在为我的CRUD应用构建一个编辑按钮。在此组件中,每个“评分”都映射到这些组件之一。该组件开始时显示的是存储在数据库中的等级,但是用户可以按编辑按钮,然后变成表格! (最终,我将获得初始值,以使用替代渲染选项中显示的数据填充表单字段)。
现在,对于编辑按钮,我有一个自定义的提交处理程序,它从两个表单字段中接收提交的数据作为“ formProps”。但是,在将这些传递给后端API之前,我还需要弄清楚如何将ID或其他内容绑定到提交处理程序。
从表单下方的组件中可以看到,整个子组件都可以访问从父级传递来的必需项,可以将其作为“ this.props.id”进行访问。在handleSubmit将所有内容都带到Redux Actions之前,是否有将'this.props.id'与formProps捆绑在一起的方法?
class Rating extends Component{
constructor(props){
super(props);
this.state = {
formClass: "notShowing",
ratingClass: "showing"
}
}
renderForm = () => {
this.state.formClass === "notShowing"
? this.setState({formClass: "showing", ratingClass: "notShowing"})
: this.setState({formClass: "notShowing", ratingClass: "showing"})
}
onSubmit = (formProps) => {
console.log("this is what the submitHandler recieves;", formProps);
this.props.editRating(formProps, () => {
this.props.history.push('/userDashboard');
});
}
render() {
const { handleSubmit, reset } = this.props;
return (
<div className="card darken-1" key={this.props._id}>
<div className={this.state.formClass}>
<form onSubmit={handleSubmit(this.onSubmit)}>
<p>What are you rating?</p>
<fieldset>
<Field
name="title"
type="text"
component="input"
autoComplete="none"
/>
<p>Add your rates!</p>
<Field
name="value"
type="number"
component="input"
autoComplete="none"
/>
</fieldset>
<button onClick={this.renderForm} type="submit" className="teal btn-flat right white-text">Submit</button>
</form>
<button onClick={this.renderForm}>Cancel</button>
</div>
<div className={this.state.ratingClass}>
<div className="card-content">
<span className="card-title">{this.props.title}</span>
<p>{this.props.value}</p>
<button onClick={this.renderForm}>Edit</button>
<button onClick={() => this.props.deleteRating(this.props.id)}>Delete</button>
</div >
</div>
</div>
);
}
}
function mapStateToProps({ratings}) {
return { ratings };
}
export default compose(
connect(mapStateToProps, actions),
reduxForm({ form: 'editRating' })
)(Rating);
答案 0 :(得分:1)
您可以使用handleSubmit
函数的第三个参数。
onSubmit = (values, _, props) => {
console.log(values, props.id);
...
}
...
const { handleSubmit, reset } = this.props;
<form onSubmit={handleSubmit(this.onSubmit)} .../>
参考:https://redux-form.com/7.4.2/docs/api/reduxform.md/#-code-onsubmit-function-code-optional-