【问题标题】:React Router 4 passing props through Route render doesn't workReact Router 4 通过 Route 渲染传递道具不起作用
【发布时间】:2023-03-09 03:23:02
【问题描述】:

有人问过这个问题,但 other answers 并没有为我解决这个问题。我想将signInWithEmail 处理函数从我的<App /> 组件向下传递到<Layout />,然后通过<Route /> 传递给<SignIn /> 组件。

执行此操作的方法显然是通过 Route 上的 render 属性,但对我来说,它只是呈现忽略了我的 onSubmit。在 React 开发工具中,我只看到了默认的 Route 道具,即使我可以在 <Layout /> 元素中看到我的处理函数显示为 props.signInWithEmail。他们没有到达<SignIn /> 元素。

我错过了什么?谢谢。

const Layout = (props) => (
// i can console.log(props) here and see props.signInWithEmail
  <div className="layout">
    // header etc...
    <main>
      <Switch>
       // ... other routes
        <Route
          path="/signin"
          render= {(props) => <SignIn onSubmit={props.signInWithEmail} />}           
        />
      </Switch>
    </main>
    // footer etc...
  </div>
)}

渲染部分应用:

  render() {
    return (
      <div className="App">
        <BrowserRouter>
          <Layout 
            signInWithEmail={this.signInWithEmail} 
            signUpWithEmail={this.signUpWithEmail} 
            signOut={this.signOut} 
            state={this.state}
          />
        </BrowserRouter>
      </div>
    );
  }

【问题讨论】:

  • 您能分享一下您是如何将道具传递到Layout 组件中的吗
  • 请展示您的应用组件。
  • 好的,我已经在传入的地方添加了应用组件,谢谢

标签: javascript reactjs react-router-dom


【解决方案1】:

这是因为您在箭头函数中覆盖了道具。 尝试像这样解构 Layout 道具:

const Layout = ({signInWithEmail}) => (
// i can console.log(props) here and see props.signInWithEmail
  <div className="layout">
    // header etc...
    <main>
      <Switch>
       // ... other routes
        <Route
          path="/signin"
          render= {() => <SignIn onSubmit={signInWithEmail} />}           
        />
      </Switch>
    </main>
    // footer etc...
  </div>
)}

【讨论】:

  • 是的,它做到了,很高兴它很简单,不敢相信我没有尝试过。谢谢。
猜你喜欢
  • 2018-05-13
  • 2018-12-19
  • 1970-01-01
  • 1970-01-01
  • 2018-06-09
  • 1970-01-01
  • 2019-08-09
  • 1970-01-01
  • 2018-02-15
相关资源
最近更新 更多