我正在尝试使用render
<Route>
在react-router 4中使用<Route>
method将道具传递给我的子组件。看到提到道具的this answer您在{react-router 3中使用的{React.cloneElement(this.props.children, { key: value })}
超过componentWillMount
。我如何通过EventEmitter
生命周期中定义的道具?具体来说,我想使用<Route>
对象。
以下是Index.js中有问题的<Route path="/screen3" render={ (props) =>
<Screen3 eventEmitter={ this.eventEmitter } {...props} />
} />
:
import React, { Component } from 'react'
import ReactDOM from 'react-dom';
import { Route, BrowserRouter, Switch, Link } from 'react-router-dom';
import { EventEmitter } from 'events';
import Screen3 from './screens/Screen3';
class App extends Component {
constructor(props) {
super(props)
this.state = {
screenIndex: 1
}
}
componentWillMount() {
this.eventEmitter = new EventEmitter()
this.eventEmitter.addListener("navigateScreen", ({screenIndex}) => {
this.updateScreen({newScreenIndex: screenIndex})
})
}
updateScreen({newScreenIndex}) {
this.setState({ screenIndex: newScreenIndex })
}
render() {
return (
<div className="app">
<div className="main-content">
{this.props.children}
</div>
</div>
)
}
}
ReactDOM.render(
<BrowserRouter>
<App>
<div>
<Route path="/screen3" render={ (props) =>
<Screen3 eventEmitter={ this.eventEmitter } {...props} />
} />
</div>
</App>
</BrowserRouter>,
document.getElementById('root')
);
完整Index.js:
import React, { Component } from 'react'
class Screen3 extends Component {
componentWillMount() {
this.props.eventEmitter.emit("navigateScreen", {screenIndex: 3})
}
render() {
return (
<div className="screen screen3">
<h1>SCREEN 3 DATA</h1>
</div>
)
}
在我的Screen3.js组件中:
export default Screen3
}
eventEmitter
当我在Screen3组件中执行console.log(this.props.eventEmitter)
时,var postsAndTagCounts = context.Posts
.Select(p => new {
PostId = p.Id,
TagCount = p.Tags.Count()
})
.OrderByDescending(p => p.Tags.Count())
.ToList();
道具未定义。有什么想法吗?