react-router v4:如何创建contentFor like功能?

时间:2018-06-03 22:04:04

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

我有这个:

import { Route } from 'react-router-dom'

const App = () => (
  <div>
    {header} // or the header block
    <Route exact path="/" component={Home} />
    <Route path="/about" component={About} />
  </div>
)

然后我的About组件看起来像这样:

const About = () => {
  // contentFor header
  const myCustomHeader = <div>About header</div>

  return (
    <div>
      About page
    </div>
  )
}

有没有办法用header组件中的App组件替换myCustomHeader组件中的About

1 个答案:

答案 0 :(得分:0)

您可以传递函数prop以更新父状态。你必须在你的路线上使用渲染而不是组件来传递道具。

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

class App extends React.Component{
    state = {
        header:"One Header"
    }

    render(){
        return (
            <div>
                {this.state.header} // or the header block
                <Route exact path="/" component={Home} />
                <Route path="/about" render={()=><About updateHeader={(newHeader)=>this.setState({header:newHeader})} />}/>
            </div>
        )
    }
}

你的关于:

import React from 'react'

class About extends React.Component{

    render(){
        this.props.updateHeader(<div>About header</div>);
        return (
            <div>
                About page
            </div>
        )
    }
}