【问题标题】:event.preventDefault not working in Reactevent.preventDefault 在 React 中不起作用
【发布时间】:2016-07-14 04:57:05
【问题描述】:

我遵循了一个教程,他们在Save 按钮上使用了event.preventDefault() 并将表单保存到状态中。我还没有真正写过input 标签,但到目前为止我已经添加了保存按钮,它有点像重新加载它不应该做的页面。

这是我的页面组件:

class manageLocationPage extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.state = {

        };
        this.SaveLocation = this.SaveLocation.bind(this);
    }

    componentWillMount() {

    }

    componentDidMount() {

    }

    SaveLocation(event) {
        event.preventDefault();
        console.log("Saved");
    }

    render() {
        return (
            <div>
                <LocationForm listingData={this.props.listingData} onSave={this.SaveLocation}/>
            </div>
        );
    }
}

我的locationForm 组件:

const LocationForm = ({listingData, onSave, loading, errors}) => {
    return (
        <form>
            <h1>Add / Edit Location</h1>
            <TextInput />

        {/*Here below is where we submit out input data*/}
            <input type="submit" disabled={loading} value={loading ? 'Saving...' : 'Save'} className="buttonSave" onClick={onSave}/>
        </form>
    );
};

我错过了什么吗?

【问题讨论】:

  • 如果你改用formonSubmit呢?

标签: javascript reactjs preventdefault


【解决方案1】:

您应该在 input.submit 上单击而不是单击它

const LocationForm = ({listingData, onSave, loading, errors}) => {
    return (
        <form  onSubmit={onSave}>
            <h1>Add / Edit Location</h1>
            <TextInput />

        {/*Here below is where we submit out input data*/}
            <input type="submit" disabled={loading} value={loading ? 'Saving...' : 'Save'} className="buttonSave"/>
        </form>
    );
};

所以事件是被阻止的表单提交。

https://facebook.github.io/react/docs/tutorial.html#submitting-the-form

【讨论】:

  • 另外,我没有包含 loading 道具,这就是它导致页面重新加载行为的原因。我已经修好了,是的,这个方法也有效。
猜你喜欢
  • 2022-01-02
  • 2016-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-20
相关资源
最近更新 更多