我正在寻找将父变量中的变量传递给子容器的良好语法.
假设我有这些路线,其上有一个全局小部件列表/和特定的小部件列表/widgets/:WidgetListID.
注意:我使用react-router-relay
<Route
path='/' component={Layout}
>
<IndexRoute
component={WidgetListContainer}
queries={ViewerQueries}
/>
<Route
path='/widgets/:WidgetListID'
component={WidgetListContainer}
queries={ViewerQueries}
/>
</Route>
Run Code Online (Sandbox Code Playgroud)
它是<WidgetList/>在<WidgetListContainer/>内部渲染的相同组件,<Layout/>这是我尝试传递WidgetListID变量的方式:
Layout.js
class Layout extends React.Component {
render() {
return (
<div>
...
{children}
...
</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
WidgetListContainer.js
class WidgetListContainer extends React.Component {
render () {
return (
<div>
...
<WidgetList
viewer={viewer}
/>
</div>
)
}
}
export default Relay.createContainer(WidgetListContainer, {
initialVariables: {
WidgetListID: null
},
fragments: {
viewer: …Run Code Online (Sandbox Code Playgroud) 我设法通过孩子传递上下文,但只有一次。上下文永远不会更新。然而我已经看到很多这样的例子,包括反应文档:https : //facebook.github.io/react/docs/context.html
这是我的代码:
父组件:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
window:{
height:null,
width:null
}
};
}
getChildContext() {
return {
window: this.state.window
}
}
componentDidMount () {
window.addEventListener('resize', this.handleResize.bind(this));
this.handleResize();
}
componentWillUnmount () {
window.removeEventListener('resize', this.handleResize.bind(this));
}
handleResize (){
this.setState({
window:{
width:window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth,
height:window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight
}
});
}
render() {
console.log(this.state.window);
// --> working
return (
{this.props.children}
);
}
}
App.propTypes = {
children: React.PropTypes.node.isRequired
};
App.childContextTypes …Run Code Online (Sandbox Code Playgroud)