我有这个:
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
?
答案 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>
)
}
}