由于我对React生态系统很陌生,我的描述和做事方式可能会有所不同,但我希望你能解决我的问题。
我有一个父组件,它获取从路由器注入的表单,并将状态和操作创建者映射到属性。
Container.js
import * as actionCreators from "../actionCreators";
export default class ComponentA extends React.Component {
render() {
return (
<div className="ComponentA">
{this.props.children} //<--Form
</div>
);
}
}
function mapStateToProps(state) {
return {
listItems: state.get("listItems")
};
}
export const Container = connect(mapStateToProps, actionCreators)(ComponentA);
使用{this.props.children}
进行渲染的组件是以下形式。
Form.js
class Form extends React.Component {
static propTypes = {
fields: PropTypes.object.isRequired,
handleSubmit: PropTypes.func.isRequired
};
render() {
const { fields: {title, description}, handleSubmit} = this.props;
return (
<div className="create-project-form">
<h1>Create Project</h1>
<form onSubmit={handleSubmit}>
<label htmlFor="title">Title</label>
<input type="text" name="title" id="title" className="form-control"/>
<label htmlFor="description">Description</label>
<textarea name="description" id="" cols="30" rows="10" className="form-control"></textarea>
<button className="btn btn-danger" onClick={handleSubmit}>Create</button>
</form>
</div>
)
}
}
export default connectReduxForm({
form: "from",
fields: ["title", "description"]
})(Form);
路由器
const routes = <Route component={App}>
<Route path="/" component={Container}/>
<Route path="/a" component={Container}>
<Route path="/a/create" component={Form}/>
</Route>
</Route>;
render(
<div>
<Provider store={store}>
<Router>{routes}</Router>
</Provider>
</div>,
document.getElementById("content"));
问题是handleSubmit
未定义,但不是我的行为。我实际上并不期望它被神奇地设置为正确的actionCreator,但我如何传递这个功能呢?我尝试了操作名称而不是handleSubmit
但是函数未定义。我看到的每个例子都会手动将handleSubmit函数传递给Form组件,但我不能这样做,因为Form是由路由器设置的。
感谢
答案 0 :(得分:7)
两件事:
<input>
。 <input
type="text"
{...title} // <-------- that (it contains the "name" prop)
className="form-control"/>
handleSubmit
: <form onSubmit={handleSubmit(data => {
// do your submit stuff here and return a Promise if you want the
// this.props.submitting flag to be set for the duration of the promise
})}>
这有帮助吗? See also