【问题标题】:React submit form button inside link component在链接组件中反应提交表单按钮
【发布时间】:2020-03-27 10:16:29
【问题描述】:

表单中的提交按钮应该执行其分配的功能并通过返回主页关闭组件,但是如果将按钮包裹在Link组件中,则该功能被取消。任何想法如何避免这种情况?

<Link to={{ pathname: "/"}} ><button type="submit" value="Submit">Save</button></Link>
handleEditFormSubmit = (index, e) => {
  if (!this.canBeSubmitted()) {
    e.preventDefault();
    return alert("Please fill all empty text spaces");
  } 
  e.preventDefault();
  let products = [...this.state.products];
  products.splice(index, 1, {name: this.state.name,
    ean: this.state.ean,
    type: this.state.type,
    weight: this.state.weight,
    color: this.state.color,
    active: false})
  this.setState({ products, name: "", ean: "", type: "", weight: "", color: "", active: false},
  () => {
    this.props.history.push("/");
  }
  );
  }

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    重定向到主页的更好方法是在函数中使用历史记录。

    submitHandler=()=>{
      //do all operation here after this navigate to home page like below example.
       this.props.history.push("/");
    }
    

    示例供您参考

      submitHandler=()=>{
       this.setState({name:'Hello'},()=>{
         this.props.history.push("/");
       })
      }
    

    您可以查看此工作演示并了解如何操作。

    https://codesandbox.io/s/react-router-46dw8

    【讨论】:

    • 不幸的是,我得到 this.props.history is undefined 错误。据我所知,新的反应版本使用 BrowserRouter 而不是历史记录。我还添加了提交功能以防万一。
    • 感谢,这里是:codesandbox.io/s/github/LukasSkarnulis/talech-task。 app 组件有提交功能,Editprod 组件包含提交按钮,应该做这个功能并返回首页。
    • 通过使用重定向组件并添加新状态来解决这个问题。感谢您的帮助。
    猜你喜欢
    • 2022-07-05
    • 2020-04-09
    • 2019-08-25
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 1970-01-01
    • 2021-09-14
    • 1970-01-01
    相关资源
    最近更新 更多