【问题标题】:TypeScript (ReactJS) compiler error, this implicitly has type anyTypeScript (ReactJS) 编译器错误,这隐含类型为 any
【发布时间】:2017-12-14 15:50:28
【问题描述】:

我有一个用 TypeScript 编写的 React 组件:

class App extends React.Component<props> {

  constructor(props) {
    super(props);
    this.treeNavElement = this.treeNavElement.bind(this);
  }

  treeNavElement() {
    return (
      <div></div>
    )
  }

  render() {
    return (
      <div>
        {
          this.props.NavDataTree.map(function(elem) {
            return <div key={elem.id} onClick={this.treeNavElement}>{elem.name}</div>
          }, this)
        }
      </div>
    )
  }
}

export default App;

我的问题是打字稿编译器对我大喊大叫,因为这行:

return <div key={elem.id} onClick={this.treeNavElement}>{elem.name}</div>

说:

[ts] 'this' 隐含类型 'any' 因为它没有类型注释。

在 map 函数之外,在 map 的第二个参数和 this.props 中可以正常工作,但在 onClick 内部 this 丢失了。

如果我在tsconfig.json 中设置"noImplicitThis": false 很好,但我想知道是否有办法在不关闭implicitthis 的情况下解决这个问题?

【问题讨论】:

  • 如果使用箭头函数会怎样?
  • 同理。
  • @Explosino Pills 的意思是...map((elem) =&gt; { ... })
  • 我知道他的意思,这并没有改变 this 在编译时在 map 内部是未知的。再说一遍:这是一个编译时问题,用 any 核对 this 和运行时零问题。
  • 抱歉,这适用于this,但现在出现了不同的错误。

标签: reactjs typescript


【解决方案1】:

你使用了function,所以this丢失了。

this.props.NavDataTree.map(function(elem) { })

如果您知道运行时function(this: XXX) {} 是什么,您可以输入this。或者你可以使用箭头操作符,所以this 被传播到函数中

this.props.NavDataTree.map(elem => { this.XXX })

【讨论】:

  • 这完全是编译时问题。如果我用noImplicitAny 抑制它,我就没有运行时问题。我不认为this 丢失了。由于 this 绑定规则,它将位于回调函数体中,但在 render() 内部它应该可用,因为我专门为 map 的 thisArg 参数提供了 this。 From mozilla docs: thisArg 执行回调时用作 this 的值。 所以 this 应该在编译时在 map 中可用。
【解决方案2】:

这是一个快速修复,将以下行添加到 tsconfig.js。

 "noImplicitThis": false,               

在隐含“any”类型的“this”表达式上引发错误。

【讨论】:

    猜你喜欢
    • 2019-08-04
    • 2018-08-23
    • 2020-12-17
    • 2021-12-11
    • 2013-09-14
    • 1970-01-01
    • 2020-09-28
    • 2020-07-30
    • 1970-01-01
    相关资源
    最近更新 更多