为什么e.preventDefault()在React中不起作用?

时间:2019-04-03 00:48:39

标签: reactjs form-submit

下面的基本代码,但表单已提交并重新加载。为什么?

import React from 'react';

class TestSubmitComponent extends React.Component {
    constructor(props) {
        super(props);
    }


    formSubmitHandler = (e) => {
        e.preventDefault(); //should prevent submit, and continue below?
        console.log(e);

        console.log('hello world ! why this does NOT show in console?!')
        return false;
    }


    render() {
        return(
            <form method="POST" action="/">
                <div onSubmit={this.formSubmitHandler}>
                    <h1>Select a file to upload</h1>

                    <input type="file" accept=".txt" name="ctlFileInput"></input>

                    <p/>
                    <input type="submit" value="Click to submit" />
                </div>
            </form>
        )
    }
}

export default TestSubmitComponent;

2 个答案:

答案 0 :(得分:2)

您的formSubmitHandler()方法实际上没有触发,因此自onSubmit()以来,每次提交表单时默认的页面刷新行为都是回调需要绑定到您的form元素:

 <form onSubmit={this.formSubmitHandler}>

此外,我将删除对服务器上POST路由的/请求。这是在您的form元素中定义的,但这不是必需的,因为这将调用您的服务器,而不是触发您的formSubmitHandler()方法。也许您可以尝试以下方法:

import React from 'react';

class TestSubmitComponent extends React.Component {
    constructor(props) {
        super(props);
    }


    formSubmitHandler = (e) => {
        e.preventDefault(); //should prevent submit, and continue below?
        console.log(e);
        console.log('hello world ! why this does NOT show in console?!')
        return false;
    }


    render() {
        return(
            <form onSubmit={this.formSubmitHandler}>
                <div>
                    <h1>Select a file to upload</h1>

                    <input type="file" accept=".txt" name="ctlFileInput"></input>

                    <p/>
                    <input type="submit" value="Click to submit" />
                </div>
            </form>
        )
    }
}

export default TestSubmitComponent;

希望有帮助!

答案 1 :(得分:0)

onSubmit在表单之后被写为div元素的属性,因此它没有按预期工作。表单提交后页面正在加载,因为表单的Submit事件不受控制。

如果将其移动到表单元素,它将起作用。

示例

<form method="POST" action="/" onSubmit={this.formSubmitHandler}>
                <div>
                    <h1>Select a file to upload</h1>

                    <input type="file" accept=".txt" name="ctlFileInput"></input>

                    <p/>
                    <input type="submit" value="Click to submit" />
                </div>
            </form>