【问题标题】:How to pass props to React router [duplicate]如何将道具传递给 React 路由器 [重复]
【发布时间】:2019-05-01 08:04:40
【问题描述】:

我正在尝试使用 react 路由器将 props 传递给组件,如下所示:

   <Login
            id={this.state.id}
            password={this.state.password}
            onChange={this.onChange}
            onSubmit={this.onSubmit}
            error={this.state.error}
          />

除了使用 react 路由器外,我该如何做到这一点,以及如何在组件本身中使用它?

我试过了,但它不起作用:

  <Route
            path="/"
            component={Login}
            components={{
              id: this.state.id,
              password: this.state.password,
              onChange: this.onChange,
              onSubmit: this.onSubmit,
              error: this.state.error
            }}
          />

【问题讨论】:

    标签: reactjs router


    【解决方案1】:

    创建Login 组件作为路由的子组件:

    <Route path="/">
        <Login id={this.state.id} ... />
    </Route>
    

    UPD:正如 trixn 所说,最好仅在路由匹配时使用渲染函数来渲染组件

    <Route path="/" render={ () => (
        <Login id={this.state.id} ... />
    )}/>
    

    【讨论】:

    • 小心,Route 的孩子总是被渲染,不管路径是否匹配。要渲染比赛,请使用 render 道具。
    • trixn 你能写一个描述如何使用渲染道具的回答吗?我在任何地方都找不到合适的语法。
    • @AlexK 请检查重复的帖子
    • 如果您尝试正确阅读问题和答案,无论如何&lt;Route path="/" render={(props) =&gt; &lt;Login {...props} id= {this.state.id} password= {this.state.password} onChange={this.onChange} onSubmit={this.onSubmit} error={this.state.error} /&gt;} /&gt;
    猜你喜欢
    • 2018-06-17
    • 2021-04-12
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 2018-08-22
    • 1970-01-01
    • 2021-12-21
    • 2023-03-31
    相关资源
    最近更新 更多