[英]Props is a deprecated symbol in React with Typescript
I have a problem: My IDE is complaining about deprecation. 我有一个问题:我的IDE抱怨弃用。
I use react 16 and typescript 2.5.3 我使用react 16和typescript 2.5.3
Following code given: 以下代码给出:
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;
At this point I am getting at props.ref 'Property ref does not exist on Partial' 在这一点上,我得到props.ref'部分'不存在属性引用'
When I extend my interface IProps, like this: 当我扩展我的界面IProps时,像这样:
interface IProps extends Props {
id: string;
}
At this point my IDE suggest to add an Generic Type 此时我的IDE建议添加Generic Type
interface IProps extends Props<any> {
id: string;
}
Now I get deprecation warning to consult online docs, BUT I do not find anything. 现在我得到弃用警告以咨询在线文档,但我没有找到任何东西。 BUT my initial error with ref-property is gone.
但我对ref-property的初始错误消失了。
Now my question: How to deal with this when I use a StatelessComponent? 现在我的问题:当我使用StatelessComponent时如何处理这个问题? How to deal with it, when Using Component (or is there no error)?
使用组件时如何处理它(或者没有错误)? And how can I avoid any?
我怎么能避免任何?
Thanks for helping me 谢谢你的帮助
You've accidentally masked the real problem by extending Props<T>
! 你通过扩展
Props<T>
意外地掩盖了真正的问题! There's a comment in the type definitions explaining why that interface is deprecated: 类型定义中有注释,解释了为什么不推荐使用该接口:
This was used to allow clients to pass
ref
andkey
tocreateElement
, which is no longer necessary due to intersection types.这用于允许客户端将
ref
和key
传递给createElement
,由于交集类型,这不再是必需的。
In other words, you used to have to extend Props<T>
for your prop type definitions so that ref
/ key
/ children
would be included, but new features in TypeScript have made this unnecessary. 换句话说,您曾经必须为您的道具类型定义扩展
Props<T>
,以便包含ref
/ key
/ children
,但TypeScript中的新功能使得这不必要。 You can just pass in a plain interface as you were doing initially. 您可以像最初一样传入一个简单的界面。
However, this still leaves you with your 'Property ref does not exist' error - this is because you cannot use refs on stateless functional components . 但是,这仍然会让您的“属性引用不存在”错误 - 这是因为您无法在无状态功能组件上使用引用 。 The type definitions are actually doing the right thing here and stopping you from writing code that won't work!
类型定义实际上是在这里做正确的事情,并阻止你编写无法工作的代码!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.