【问题标题】:What is the type of "children" in nested routes in react-router?react-router中嵌套路由中的“子”类型是什么?
【发布时间】:2016-06-02 12:38:36
【问题描述】:

给定以下代码,“孩子”的类型是什么?似乎很可能只是React.Component,但我不确定,并且无法仅通过仔细阅读代码来解决这个问题。鉴于您可以在路线中拥有“组件”,我绝对不确定。

此外,由于编译器错误“错误 TS2314:通用类型'组件'需要 2 个类型参数”,因此仅使用 React.Component 失败,所以也许我可以这样做 React.Component<{}, {}>

export class App extends React.Component<{children}, {}> {
    public render() {
        return (
            <div>
                <h1>React Router Tutorial</h1>
                <ul role="nav">
                    <li><Link to="/about">About</Link></li>
                    <li><Link to="/repos">Repos</Link></li>
                </ul>

                {this.props.children}
            </div>
        );
    }
}

ReactDOM.render((
    <Router history={hashHistory}>
        <Route path="/" component={App}>
            <Route path="/repos" component={Repos}/>
            <Route path="/about" component={About}/>
        </Route>
    </Router>
), document.getElementById('app'));

为了澄清,我还要换一种方式问这个问题:假设我想用以下内容替换第一行,我会给children,而不是any,我会给出什么类型

interface {
    children: /* ??? something besides any */ any
}

export class App extends React.Component<AppProps, {}> { /* ... */ }

【问题讨论】:

  • 我刚刚在 react.d.ts 中发现了 ReactInstance,它只是 Component&lt;any, any&gt; | Element 的类型别名——这似乎也很有希望:D
  • 看来React.ReactElement其实更合适。
  • 我想知道这里的 children 是否实际上是 React 的一部分(不是 react-router),而 props 应该只是扩展 React.Props 的东西; React.Props 包含一个 ReactNode 类型的“子”属性。

标签: reactjs typescript react-router


【解决方案1】:

似乎在react-router.d.ts in DefinitelyTyped 中演示了正确的方法。对于众所周知的路由器组件。)

在 React 类型中,有一个 Props 接口,其中包含 children 等 React 组件的标准属性。

因此,代码示例转换为以下内容。特别注意顶部的界面。

interface AppProps extends React.Props<App> { }

export class App extends React.Component<AppProps, {}> {
    /* ... */
}

【讨论】:

    猜你喜欢
    • 2015-02-21
    • 1970-01-01
    • 2021-12-30
    • 2017-06-25
    • 2016-01-30
    • 1970-01-01
    • 2016-03-06
    • 2017-11-11
    相关资源
    最近更新 更多