daz*_*ous 5 javascript typescript reactjs
我有一个问题:我的 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;
Run Code Online (Sandbox Code Playgroud)
在这一点上,我得到了 props.ref 'Property ref does not exist on Partial'
当我扩展接口 IProps 时,如下所示:
interface IProps extends Props {
id: string;
}
Run Code Online (Sandbox Code Playgroud)
此时我的 IDE 建议添加一个 Generic Type
interface IProps extends Props<any> {
id: string;
}
Run Code Online (Sandbox Code Playgroud)
现在我收到弃用警告以查阅在线文档,但我什么也没找到。但是我对 ref-property 的初始错误消失了。
现在我的问题是:当我使用 StatelessComponent 时如何处理这个问题?使用组件时如何处理(或没有错误)?我怎样才能避免呢?
谢谢你帮助我
您通过扩展不小心掩盖了真正的问题Props<T>!类型定义中有一条注释解释了为什么不推荐使用该接口:
这用于允许客户端通过
ref和key到createElement,由于交叉点类型而不再需要。
换句话说,你曾经有过以延长Props<T>你的道具类型定义,以便ref/ key/children将被包括在内,但在打字稿新功能使这个必要。您可以像最初一样传入一个简单的界面。
但是,这仍然会给您留下“属性引用不存在”错误 - 这是因为您不能在无状态功能组件上使用引用。类型定义在这里实际上是在做正确的事情,并阻止您编写不起作用的代码!