具有Typescript的onChange TextField兼容性

时间:2019-01-07 20:51:22

标签: reactjs typescript material-ui

我对使用Typescript和Material-UI还是很陌生,我在输入事件处理程序时遇到了问题。

我有一些TextField组件,它们的输入是十六进制代码,将更改应用程序中其他某些组件的CSS颜色。如果十六进制代码通过了验证测试,我将呈现一个常规文本字段。如果没有,我将显示一个错误文本字段。

这是渲染主体中的样子:{this.renderHexTextField(this.state.primaryColor, 'primaryColor')}

我在Stack Overflow和MUI github上也遵循了一些类似的问题,但是我的代码中出现错误。

interface IBrandingState {
primaryColor: string
secondaryColor: string
userResponseColor: string
chatBackground: string
userBoxColor: string
hoverFillColor: string
hoverFontColor: string
}

private renderHexTextField(input: string, name: string) {
// name parameter used to specify which state in handleChange function
if (this._throwHexErr(input) === 'True') {
  // If hex format is correct, render normal text field
  return (
    <TextField
      required={true}
      id="standard-required"
      margin="normal"
      name={name}
      placeholder={input}
      onChange={this.handleChange}
    />
  )
} else {
  // else render error text field
  return (
    <TextField
      error={true}
      id="standard-error"
      margin="normal"
      name={name}
      placeholder={input}
      onChange={this.handleChange}
    />
  )
 }
}    

private handleChange = (event: React.FormEvent<HTMLElement>): void => {
  this.setState({ [event.currentTarget.name]: event.currentTarget.value })
}

在VSCode中,我的handleChange函数第二行出现错误,提示:

Argument of type '{ [x: number]: any; }' is not assignable to parameter of type
'IBrandingState | ((prevState: Readonly<IBrandingState>, props: Readonly<IBrandingProps>)
=> IBrandingState | Pick<IBrandingState, "primaryColor" | "secondaryColor" | ... 4 more 
... | "hoverFontColor"> | null) | Pick<...> | null'.
 Type '{ [x: number]: any; }' is not assignable to type 'Pick<IBrandingState,
"primaryColor" | "secondaryColor" | "userResponseColor" | "chatBackground" | "userBoxColor" |
"hoverFillColor" | "hoverFontColor">'.

Property 'primaryColor' is missing in type '{ [x: number]: any; }'. [2345]"

所以我很好奇这个{ [x: number]: any; }的来源,也许我需要扩展状态接口的类型?在我看来,我已经根据this previous question.预先正确地键入了事件,谢谢,如果我需要提供更多代码,请告诉我。

0 个答案:

没有答案
相关问题