javascript - Props 是 React with Typescript 中已弃用的符号

标签 javascript reactjs typescript

我有一个问题:我的 IDE 提示弃用。

我使用 react 16 和 typescript 2.5.3

给出以下代码:

import React, { Props, StatelessComponent } from 'react';
import PropTypes from 'prop-types';

interface IProps {
    id: string;
}

const Foo: StatelessComponent<IProps> = (props: IProps) => {
    props.ref = nodeRef;
    return (<div id={props.id}></div>);
};

Foo.propTypes = {
    id: PropTypes.string,
};

Foo.defaultProps = {
    id: 'bar',
};

export default Foo;

此时我得到 props.ref 'Property ref does not exist on Partial'

当我扩展我的接口(interface) IProps 时,像这样:

interface IProps extends Props {
    id: string;
}

此时我的IDE建议添加一个通用类型

interface IProps extends Props<any> {
    id: string;
}

现在我在查阅在线文档时收到弃用警告,但我没有找到任何东西。但是我最初的 ref-property 错误消失了。

现在我的问题是:当我使用 StatelessComponent 时如何处理这个问题? Using Component时如何处理(或者没有报错)?我怎样才能避免呢?

谢谢你帮助我

最佳答案

您通过扩展 Props<T> 不小心掩盖了真正的问题!类型定义中有一条注释解释了为什么不推荐使用该接口(interface):

This was used to allow clients to pass ref and key to createElement, which is no longer necessary due to intersection types.

换句话说,您过去必须扩展 Props<T>对于您的 Prop 类型定义,以便 ref/key/children会被包括在内,但是 TypeScript 中的新特性使它变得不必要了。您可以像最初一样传入一个普通界面。

但是,这仍然会给您带来“属性引用不存在”错误 - 这是因为 you cannot use refs on stateless functional components .类型定义实际上在这里做了正确的事情,并阻止您编写不起作用的代码!

关于javascript - Props 是 React with Typescript 中已弃用的符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47714850/

相关文章:

javascript - 如何在 native react 中从其类实例化组件

html - Angular 4 - 如何显示继承类组件的模板

angular - TS2564 属性 mapViewEl 没有初始化程序

javascript - 使用 JavaScript 脚本可靠地检测 InDesign Server 中 TextFrame 中的文本溢出?

css - flexbox 没有在 React 中包装内容

javascript - RubyMine 代码重新格式化不尊重 ESLint 配置

html - 设置包装器样式但不将样式传播到子元素的最聪明的方法是什么?

javascript - TypeScript 中是否有可用于 HTML 元素的类?

javascript - ui-bootstrap timepicker 和 ng-model 值转换器

javascript - 如何将这个基于 ID 的对象变成一个对象数组?