使用TypeScript

时间:2019-02-19 15:03:20

标签: reactjs typescript

我正在用TypeScript编写React应用。 我组件的状态如下:

type UploadState = {
  ...
  modal: string | null
  ...
}

在我的render中,我有:

render() {
  return <div>{this.renderModal()}</div>
}

我在代码中的某个位置:

this.setState({ modal: 'mappingModal' })

最后renderModel是:

renderModal = () => {
  if (this.state.modal === null) {
    return
  }
  return this[modal as keyof this]() //It doesn't work
}

我期望返回值为mappingModal

mappingModal = () => {
  return <h1>Some text or whatever!</h1>
}

但是由于()中的this[modal as keyof this]()导致出现此错误:

Cannot invoke an expression whose type lacks a call signature.
Type '{}' has no compatible call signatures.ts(2349)

如果我删除(),则会在浏览器中收到此错误:

Warning: Functions are not valid as a React child.
This may happen if you return a Component instead of <Component /> from render.
Or maybe you meant to call this function rather than return it.

有解决方案吗?

更新(可能的答案)

看来,如果我使用this[modal as keyof Upload]()-并且Upload当然是我的组件名称-我不会有任何问题。希望它不会引起任何将来的错误

1 个答案:

答案 0 :(得分:0)

看来,如果我使用this[modal as keyof Upload]()-并且Upload当然是我的组件名称-我不会有任何问题。像这样:

class Upload extends React.Component<UploadProps, UploadState> {
  ...
  renderModal = () => {
    if (this.state.modal === null) {
      return
    }
    return this[modal as keyof Upload]()
  }
  ...
}