在React.js中设置onSubmit

在React.js中设置onSubmit

问题描述:

在提交表单时,我正在尝试 doSomething()而不是默认的帖子行为。

On submission of a form, I'm trying to doSomething() instead of the default post behaviour.

显然在React中, onSubmit是表单支持的事件。但是,当我尝试以下代码时:

Apparently in React, onSubmit is a supported event for forms. However, when I try the following code:

var OnSubmitTest = React.createClass({
    render: function() {
        doSomething = function(){
           alert('it works!');
        }

        return <form onSubmit={doSomething}>
        <button>Click me</button>
        </form>;
    }
});

运行方法 doSomething(),但此后,仍然执行默认的帖子行为。

The method doSomething() is run, but thereafter, the default post behaviour is still carried out.

您可以在我的 jsfiddle 中进行测试。

You can test this in my jsfiddle.

我的问题:如何防止默认的帖子行为?

My question: How do I prevent the default post behaviour?

doSomething()函数中,传递事件 e 并使用 e.preventDefault ()

In your doSomething() function, pass in the event e and use e.preventDefault().

doSomething = function (e) {
    alert('it works!');
    e.preventDefault();
}