小编tre*_*rsg的帖子

在TypeScript中将forwardRef组件与子代一起使用

使用@ types / react 16.8.2和TypeScript 3.3.1。

我直接从React文档中提出了这个前向引用示例,并添加了几个类型参数:

const FancyButton = React.forwardRef<HTMLButtonElement>((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef<HTMLButtonElement>();
<FancyButton ref={ref}>Click me!</FancyButton>;
Run Code Online (Sandbox Code Playgroud)

我在下一行的最后一行中收到以下错误FancyButton

类型“ { children: string; ref: RefObject<HTMLButtonElement>; }”不能分配给类型“ IntrinsicAttributes & RefAttributes<HTMLButtonElement>”。属性' children'在类型' IntrinsicAttributes & RefAttributes<HTMLButtonElement>'.ts 中不存在(2322)

看来React.forwardRef的返回值的类型定义是错误的,没有正确地合并在子道具中。如果我<FancyButton>自行关闭,错误就会消失。缺少针对该错误的搜索结果,使我相信自己缺少明显的东西。

jsx typescript reactjs tsx

8
推荐指数
3
解决办法
2722
查看次数

标签 统计

jsx ×1

reactjs ×1

tsx ×1

typescript ×1