我想在用户提交表单时捕获表单值。React 教程显示了这一点:
var CommentForm = React.createClass({
handleAuthorChange: function(e) {
this.setState({author: e.target.value});
},
handleTextChange: function(e) {
this.setState({text: e.target.value});
},
handleSubmit: function(e) {
e.preventDefault();
var author = this.state.author.trim();
var text = this.state.text.trim();
if (!text || !author) {
return;
}
render: function() {
return (
<form className="commentForm" onSubmit={this.handleSubmit}>
这种风格通过每个输入的处理函数将所有更改推入状态。如果我要全面使用 Redux,我相信我会在其中添加动作和动作创建者,这似乎是很多开销。
注意参数 tohandleSubmit
是一个事件。
我遇到了以下 React/Redux 入门工具包,它看起来更容易使用。它使用智能/容器组件和哑/演示组件组合:
@connect(
() => ({}),
{initialize})
export default class Survey extends Component {
...
handleSubmit = (data) => {
window.alert('Data submitted! ' + JSON.stringify(data));
this.props.initialize('survey', {});
}
render()
return ( <SurveyForm onSubmit={this.handleSubmit}/> )
...
class SurveyForm extends Component {
static propTypes = {
handleSubmit: PropTypes.func.isRequired,
}
render() {
const { handleSubmit } = this.props;
return (
<div>
<form className="form-horizontal" onSubmit={handleSubmit}>
...
}
}
我不清楚的是,为什么表单处理程序的onSubmit
处理程序会为其 Facebook 教程的参数接收一个事件,但为什么入门工具包的onSubmit
处理程序正在获取表单数据......入门工具包正在利用该redux-form
包,但我看不到它直接影响该处理程序的行为方式。