反应教程:CommentForm的onSubmit不起作用

时间:2015-09-10 20:06:00

标签: reactjs

教程:http://facebook.github.io/react/docs/tutorial.html

var CommentForm = React.createClass({
    handleSubmit: function(e) {
        console.log("form submit");
        e.preventDefault();
        var author = React.findDOMNode(this.refs.author).value.trim();
        var text = React.findDOMNode(this.refs.text).value.trim();
        if (!text || !author) {
            return;
        }
        this.props.onCommentSubmit({author: author, text: text}); // used in CommentBox (callback when the form is sent)
        React.findDOMNode(this.refs.author).value = '';
        React.findDOMNode(this.refs.text).value = '';
        return;
    },
    render: function() {
        return (
            <div className="commentForm" onSubmit={this.handleSubmit}>
                 {/* IMPORTANT: closing each tag is MANDATORY in JSX. e.g. <br/> VS <br>*/}
                <input type="text" placeholder="Your name" ref="author" />
                <input type="text" placeholder="Say something..." ref="text" />
                <input type="submit" value="Post" />
            </div>
        );
    }
});

表单已呈现,但是当我点击提交时,没有任何反应,甚至是console.log。

1 个答案:

答案 0 :(得分:2)

在示例中,他们使用元素。当触发此表单中的输入提交时,将触发onSubmit事件。这不适用 只需将<div>替换为<form>即可解决问题:)

...
render: function() {
        return (
            <form className="commentForm" onSubmit={this.handleSubmit}>
                 {/* IMPORTANT: closing each tag is MANDATORY in JSX. e.g. <br/> VS <br>*/}
                <input type="text" placeholder="Your name" ref="author" />
                <input type="text" placeholder="Say something..." ref="text" />
                <input type="submit" value="Post" />
            </form>
        );
    }