jsx-control-statements避坑指南

babel-plugin-jsx-control-statements是jsx的babel增强插件,可以让我们在jsx里用组件的方式写条件渲染代码

使用前:

render () {
    return (
        <div>
            {'some condition' ?  <span>true</span> : null}
        </div>
    )
}

使用后:

render () {
    return (
        <div>
            <If condtion={'some condition'}>
                <span>true</span>
            </If>
        </div>
    )
}

具体安装和使用方法去官方文档翻阅一下,并不复杂

在typescript项目中使用时需要引入d.ts文件,通常做法是在项目根目录的app.d.ts(可能是其它名称)最上方通过reference引用

/// <reference types="node" />
/// <reference types="react" />
/// <reference types="react-dom" />
/// <reference types="babel-plugin-jsx-control-statements" />

看着一切正常,但是当使用react-transition-group或一些其它库时会导致children的类型推导失败,显示错误为"没有与此匹配的重载",原因是babel-plugin-jsx-control-statements重写了JSX,添加了children的类型声明,该children声明未包含ReactNode类型

处理方法如下:

  1. 取消reference引入babel-plugin-jsx-control-statements
  2. 将node_modules/babel-plugin-jsx-control-statements/index.d.ts的内容复制到app.d.ts内
  3. 将ReactNode的类型补充到TChildren中
// ... babel-plugin-jsx-control-statements/index.d.ts的其它内容
declare namespace JSX {
  type TChildren = React.ReactNode | Element | string | number | boolean | null | typeof undefined;

  interface IntrinsicAttributes {
    children?: TChildren | TChildren[];
  }
}

评论

暂无评论