mar*_*llo 6 typescript reactjs
我有一个用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;
Run Code Online (Sandbox Code Playgroud)
我的问题是打字稿编译器对我大吼大叫,因为这行:
return <div key={elem.id} onClick={this.treeNavElement}>{elem.name}</div>
Run Code Online (Sandbox Code Playgroud)
他说:
[ts]'this'隐式具有类型'any',因为它没有类型注释.
在map函数之外,在map第二个参数中,this.props它工作正常,但内部onClick this丢失.
如果我设置"noImplicitThis": false的tsconfig.json是好的,但我想知道是否有办法解决头也不回implicitthis了吗?
你用了function,那么this就失去了。
this.props.NavDataTree.map(function(elem) { })
Run Code Online (Sandbox Code Playgroud)
this如果您在运行时知道这是什么,则可以键入function(this: XXX) {}。或者您可以使用箭头运算符,因此this传播到函数中
this.props.NavDataTree.map(elem => { this.XXX })
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2428 次 |
| 最近记录: |