【问题标题】:Pass Props to this.props.children将 Props 传递给 this.props.children
【发布时间】:2018-10-24 19:23:10
【问题描述】:

我是 React 新手,在将自定义道具传递给 this.props.children 时遇到问题。我已经尝试过React.cloneElement,当我在创建它的类中执行 console.log 时可以看到该道具,但是当我尝试通过它时它会丢失。我不知道React-Router-Dom 是否正在做某事导致道具无法通过。任何帮助将不胜感激。

我使用来自 GitHub 的 Create-React-App 开始了这个项目。我安装了以下软件。

"react": "^16.3.2",
"react-dom": "^16.3.2",
"react-redux": "^5.0.6",
"react-router-dom": "^4.2.2",
"react-scripts": "1.1.4",
"redux": "^3.7.2",

在 App.js 中

render() {
 return (
  <Provider store={store}>
    <BrowserRouter> 
    <Switch>
      <Route exact path="/" component={LoginPage} />
      <Route path="/Login" component={LoginPage} />
      <RootPage>
        <Route path="/TestPage" component={testPage} />
      </RootPage> 
    </Switch>
   </BrowserRouter>
  </Provider>
 );
}

在 RootPage.js(父)中

render() {
    const { classes, theme, children } = this.props;

    var childrenWithProps = React.Children.map(children, child => React.cloneElement(child, { doSomething: "Test String" }));

    console.log(childrenWithProps)
    return (
        <div>
           {childrenWithProps}
        </div>
    );
}

RootPage.js 中使用上面的console.log,我可以看到道具“doSomething”。

在 TestPage.js(子)中

render(){
    const { classes, theme } = this.props;

    console.log(this.props)

    return (
        <div> 
        </div>
    );
}

在上面的 console.log 在 TestPage.js 中我没有看到我通过的“doSomething”道具。

感谢您的帮助。

【问题讨论】:

    标签: javascript reactjs redux react-router-v4 react-router-dom


    【解决方案1】:

    propsRoute 组件传播到TestPage 组件。

    <RootPage>
      <Route path="/TestPage" render={props => <TestPage {...props} /> }/>
    </RootPage>
    

    【讨论】:

    • 感谢您的快速回复,我尝试了您所拥有的,并且能够从 App.js 传递道具,但我确实需要从 RootPage.js 传递它们。根页面有TestPage需要调用的功能。也许我错过了一些东西,有没有办法使用你上面的东西来做到这一点?
    • 我想,你错过了我的观点。我已经编辑了答案。再次验证。
    • 我是 React 新手,更不用说整个 Web 开发人员的事情了。我知道,如果我在声明路由的 App.js 文件中有函数和状态,我可以使用你所拥有的。我只是不明白如何使用上面的代码从 TestPage.js 中触发一个存在于 RootPage.js 中的函数。 RootPage 将是我的标题和侧导航栏所在的位置,因此需要在其中调用函数。如果我遗漏了什么,请您指出正确的方向来学习它。我应该将这些功能移至 app.js 吗?
    猜你喜欢
    • 2019-01-07
    • 2016-06-20
    • 2020-04-07
    • 2019-08-11
    • 2019-03-18
    • 2020-05-28
    • 1970-01-01
    相关资源
    最近更新 更多