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

Pat*_*ick 29 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')
);
Run Code Online (Sandbox Code Playgroud)

App.js

  render: function() {
    return (
      <div>
        <Header />
        {this.props.children}
      </div>
    );
  }
Run Code Online (Sandbox Code Playgroud)

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

azi*_*ium 32

这个问题归结为,你如何向儿童传递道具?

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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为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>
)
Run Code Online (Sandbox Code Playgroud)

在codesandbox上的示例

我以前的oldschool回答我不再推荐了:

使用几个React辅助方法,您可以添加状态,道具和其他任何东西 this.props.children

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

  return <div>{children}</div>
}
Run Code Online (Sandbox Code Playgroud)

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


Jes*_*ing 10

您可以使用React方法"cloneElement"来完成此任务.克隆元素时,可以在此时传递道具.在渲染fn中使用克隆而不是原始克隆.例如:

    render: function() {
    var childrenWithProps = React.cloneElement(this.props.children, {someProp: this.state.someProp});
    return (
      <div>
        <Header />
        {childrenWithProps}
      </div>
    );
  }
Run Code Online (Sandbox Code Playgroud)