[英]react-router v4: How to create a contentFor like feature?
I have this: 我有这个:
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>
)
Then my About component looks like this: 然后我的About组件如下所示:
const About = () => {
// contentFor header
const myCustomHeader = <div>About header</div>
return (
<div>
About page
</div>
)
}
Is there a way to replace the header
in the App
component with the myCustomHeader
component from the About
component ? 有没有办法用About
组件中的myCustomHeader
组件替换App
组件中的header
?
You can pass a function prop to update the parents state. 您可以传递功能道具来更新父母状态。 You'll have to use render instead of component on your Route to pass props. 您必须在路径上使用渲染而不是组件来传递道具。
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>
)
}
}
And your About : 和您的简介:
import React from 'react'
class About extends React.Component{
render(){
this.props.updateHeader(<div>About header</div>);
return (
<div>
About page
</div>
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.