reactjs - React router 和 this.props.children - 如何将状态传递给 this.props.children

标签 reactjs react-router

我第一次使用React-router,我还不知道如何思考它。以下是我在嵌套路由中加载组件的方法。

入口点.js

ReactDOM.render(
    <Router history={hashHistory} >
        <Route path="/" component={App}>
            <Route path="models" component={Content}>
        </Route>
    </Router>, 
    document.getElementById('app')
);

App.js

  render: function() {
    return (
      <div>
        <Header />
        {this.props.children}
      </div>
    );
  }

所以我的应用程序的子组件是我发送的内容组件。我正在使用 Flux,我的 App.js 具有状态并监听更改,但我不知道如何将该状态传递给此组件。 Prop .children.在使用react-router之前,我的App.js明确定义了所有子级,因此传递状态是很自然的,但我现在不知道如何做到这一点。

最佳答案

这个问题归结为,如何将 Prop 传递给 child ?

2018 年 6 月答案

当今的技术:

<小时/>

假设有一些有状态组件:

import React from 'react'
import { BrowserRouter, Route } from 'react-router-dom'

// some component you made
import Title from './Title'

class App extends React.Component {
  // this.state
  state = { title: 'foo' }

  // this.render
  render() {
    return (
      <BrowserRouter>

        // when the url is `/test` run this Route's render function:
        <Route path="/:foobar" render={

          // argument is props passed from `<Route /`>
          routeProps => 

            // render Title component
            <Title 
              // pass this.state values
              title={this.state.title}

              // pass routeProps values (url stuff)
              page={routeProps.match.params.foobar} // "test"
            />

        } />

      </BrowserRouter>
    )
  }
}

这是有效的,因为 this.props.children 是一个函数:

// "smart" component aka "container"
class App extends React.Component {
  state = { foo: 'bar' }
  render() {
    return this.props.children(this.state.foo)
  }
}

// "dumb" component aka "presentational"
const Title = () => (
  <App>
    {title => <h1>{title}</h1>}
  </App>
)

<强> Example on codesandbox

我之前的老派答案,我不再推荐:

使用几个 React 辅助方法,您可以向 this.props.children 添加状态、 Prop 和其他任何内容

render: function() {
  var children = React.Children.map(this.props.children, function (child) {
    return React.cloneElement(child, {
      foo: this.state.foo
    })
  })

  return <div>{children}</div>
}

然后您的子组件可以通过 Prop this.props.foo 访问它。

关于reactjs - React router 和 this.props.children - 如何将状态传递给 this.props.children,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35835670/

相关文章:

javascript - 类型错误 : Cannot read property 'prepareStyles' of undefined

javascript - 映射循环内的条件语句

javascript - 如何让一个按钮点击 React 中不同组件中的另一个按钮

reactjs - Nextjs 404 重新加载/刷新操作错误

reactjs - React router 4 `Link`组件仅更改url而不更新路由

javascript - "Uncaught TypeError: history.push is not a function"发生错误

javascript - 终极版 : Asynchronous action creator not being called

javascript - Object.assign 在这种情况下的行为

reactjs - URL 更改但 View 在 React Router 4 中没有更改

javascript - 如何在 React js 上使用历史记录重定向到另一个页面?