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

Why e.preventDefault() does not work in React?

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

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;

您的 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;

希望对您有所帮助!

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

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

例子

<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>