【发布时间】:2017-09-14 19:29:05
【问题描述】:
我对反应很陌生... 我有一个父组件,它代表我的 web 应用程序的背景。当用户导航到不同的路由时,我使用来自 react-router 的 Match 来处理。
新路由会渲染 PageView 组件,我希望它有不同的背景图片。所以要做到这一点,我通过将一个函数从父级传递给他的子级道具,然后在子级中从 componentDidMount() 调用它来设置它的父级的背景图像
这不起作用并给我Maximum call stack exceeded 错误
这是我的父组件:
class App extends Component {
constructor () {
super()
this.state = {
backgroundImage: '../public/img/initial.jpg'
}
this.changeBackground = this.changeBackground.bind(this)
}
changeBackground (backgroundImage) {
this.setState({
backgroundImage
})
}
render () {
return (
<BrowserRouter>
<Provider store={store}>
<div className='app' style={{backgroundImage: `url(${this.state.backgroundImage})`}}>
<div className='overlay'>
<Match exactly pattern='/' component={() => <Landing />}
/>
<Match
pattern='/healthcare'
component={(props) => <PageView descriptionText='Healthcare Solutions'
backgroundImage='../public/img/5.png' changeParentBackground={this.changeBackground} {...props} />}
/>
<Match
pattern='/officeofthefuture'
component={(props) => <PageView descriptionText='Office of the Future'
backgroundImage='../public/img/1.png' changeParentBackground={this.changeBackground} {...props} />}
/>
</div>
</div>
</Provider>
</BrowserRouter>
)
}
}
这是我的子组件 PageView
class PageView extends Component {
componentDidMount () {
const { backgroundImage, changeParentBackground } = this.props
changeParentBackground(backgroundImage)
}
render () {
const { descriptionText } = this.props
console.log(this.props.changeParentBackground)
return (
<div className='outerDiv'>
<LeftDesign show />
<RightDesign descriptionText={descriptionText} />
</div>
)
}
}
正确设计:
class RightDesign extends Component {
render () {
const { descriptionText } = this.props
return (
<div className='rightDiv'>
<div id='bigCircle'>
<div className='bigCircleTextDiv'>
<h1 className='bigCircleText'>{descriptionText}</h1>
</div>
</div>
</div>
)
}
}
左设计
class LeftDesign extends Component {
constructor (props) {
super(props)
const { show } = this.props
this.state = {show}
}
render () {
return (
<div className='leftDivContainer'>
<div className='leftDiv'>
{this.state.show && <WelcomeMsg />}
</div>
</div>
)
}
}
【问题讨论】:
-
这段代码看起来不错,我认为问题出在
LeftDesign或RightDesign组件中,你能也显示这些组件吗? -
@MayankShukla 请查看我添加了组件的已编辑问题
-
因此您可以读取父级的 Location 属性对象以确定您在哪个页面上。将 'this.props.location.pathname' 拆分为 '/' 并拉取第二个数组项以找到您的第一级路由字符串并使用 switch 语句来确定背景图像。
标签: reactjs ecmascript-6 react-router