如何防止按下提交按钮时React回发

时间:2019-07-31 05:52:42

标签: javascript reactjs react-redux

在React组件中如何防止其回发,因此当按下“提交”按钮时不会重新加载页面。

下面是组件代码:

const class MyComponent extends React.Component<IEditCampaignStateProps & IEditCampaignDispatchProps, EditCampaignState> {

  ...

  onSubmit = (e: any) => {
    const campaign: Campaign = {
      title: this.state.campaign.title,
    }
    this.props.addCampaign(campaign);
  }

  render() {
    return (
      <Container> 
         ...
      </Container> 
     )
   }
}

2 个答案:

答案 0 :(得分:2)

尝试在代码中添加一行...

 onSubmit = (e: any) => {
    e.preventDefault();
    const campaign: Campaign = {
      title: this.state.campaign.title,
    }
    this.props.addCampaign(campaign);
   }

我已经添加了..       e.preventDefault();

答案 1 :(得分:0)

我找到了答案,

根据MDN Web Docs

Event接口的preventDefault()方法告诉用户代理,如果未显式处理事件,则不应像通常那样考虑其默认操作。该事件将继续像往常一样传播,除非事件的侦听器之一调用stopPropagation()或stopImmediatePropagation(),它们中的任何一个都会终止传播。

onSubmit = (e: any) => {
    e.preventDefault();
    const campaign: Campaign = {
      title: this.state.campaign.title,
    }
    this.props.addCampaign(campaign);
   }