首页 > 解决方案 > 尝试有条件地禁用链接时的 TS2339

问题描述

在一个表中,我有一个链接,我想有条件地变灰。以下代码在更新之前运行良好:

<Link to="#"
  onClick={e => { e.preventDefault(); }}
  disabled={this.props.finalisingStatus} >
      Finalize up to here
</Link>

在标题中,我import { Link } from "react-router-dom"像往常一样做了。在组件的接口中,我定义了一个属性finalisingStatus: Boolean;

更新到 Typescript(版本 4.41.2)后,我收到 TS2339 错误:

类型“IntrinsicAttributes & IntrinsicClassAttributes> & Readonly> & Readonly<{ children?: ReactNode; 上不存在属性‘disabled’ }>'

我该如何解决?

PS:React 组件中的 TypeScript TS2339 错误:类型 'IntrinsicAttributes...' 上不存在属性 'xyz'有点相关,但在我的情况下不是问题。

标签: reactjstypescriptreact-router

解决方案


I would recommend you to render Link conditionally, as disabled might not be a valid prop of Link. This way, you will not need to worry about overwriting the click event that is triggered by Link.

If it is disabled, you render your span element with the disabled styles.

Here is a simple example:

render () {
  const { isDisabled } = this.props;
  if(isDisabled){
    return <span className='disabled'>{this.props.linktext}</span>;
  } else {
    return <Link to={this.props.to}>{this.props.linktext}</Link>;
  }
}

推荐阅读