gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:06:45 25 4
gpt4 key购买 nike

我有一个问题:我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com