ts(2683):'this'的外部值被此容器遮盖

时间:2019-08-15 12:17:39

标签: reactjs typescript semantic-ui

我正在实现onChange方法来删除上传的图像。
但是发生编译错误,所以我想知道解决方法。

前:React
css:semantic-ui-react

  constructor(props: {}) {
    super(props);
    this.state = {
      title: '',
      content: '',
      redirect: false,
      files: [],
    };
    this.handleRemove = this.handleRemove.bind(this);
  }

  handleRemove() {
// some code
}

  render() {
    return (
          <List>
            {(this.state.files || []).map(function(file, i) {
            // error occurs at onclick
              return <List.Item icon="image" content={file.name} onclick={this.handleRemove}/>;
            })}
          </List>
    );
  }

完整的源代码在这里:
https://github.com/jpskgc/article/blob/master/client/src/components/Detail.tsx

this.handleRemove上,发生以下错误。
我想解决此错误。

any
'this' implicitly has type 'any' because it does not have a type annotation.ts(2683)
Post.tsx(115, 49): An outer value of 'this' is shadowed by this container.

1 个答案:

答案 0 :(得分:1)

您必须在地图函数中使用箭头函数,以便将'this'传递到地图函数中:

map((file,I)=> {...})而不是map(function(file,I){})