我正在使用render={() => </Component />}
通过React Router 4渲染组件
我需要将状态传递给给定的组件,即:<Game />
export const Routes: React.SFC<{}> = () => (
<Switch>
<Route path="/" exact={true} component={Home} />
<Route path="/play-game" render={() => <Game {...this.state} />} />
<Redirect to="/" />
</Switch>
)
TS中断说:
The containing arrow function captures the global value of 'this' which implicitly has type 'any'
最终目标是能够将Routes
传递到我的主应用程序:
export default class App extends Component<{}, AppState> {
public state = {
// state logic
}
public render(): JSX.Element {
return (
<BrowserRouter>
<div className="App">
<Navigation />
<Routes />
</div>
</BrowserRouter>
)
}
}
如何应用正确的类型来抑制此TypeScript错误?
答案 0 :(得分:2)
箭头函数没有词法上下文,因此在箭头主体内对this
的任何调用都会在其外部范围内退化为它的值。这就是TS的抱怨。
对于传递状态的问题,您需要将其作为道具传递给Routes
组件,然后将其分派到相关的路线。
export default class App extends Component<{}, AppState> {
public state = {
// state logic
}
public render(): JSX.Element {
return (
<BrowserRouter>
<div className="App">
<Navigation />
<Routes state={this.state}/>
</div>
</BrowserRouter>
)
}
}
// you need to pass the correct type to React.SFC<>
// probably something along React.SFC<{ state: State }>
// where State is the type of `state` field in App.
export const Routes: React.SFC<...> = ({ state }) => (
<Switch>
<Route path="/" exact={true} component={Home} />
<Route path="/play-game" render={() => <Game {...state} />} />
<Redirect to="/" />
</Switch>
)