我正在使用 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 错误?
最佳答案
箭头函数没有词法上下文,因此在箭头主体内对 this
的任何调用都将退化为其在外部范围内的值。这就是 TS 所提示的。
对于传递状态的问题,您需要将其作为 prop 传递给 Routes
组件,该组件会将其分派(dispatch)到相关路径。
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>
)
关于javascript - typescript - ReactRouter |箭头函数捕获 'this' 的全局值,隐含类型为 'any',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54185893/