【问题标题】:Property 'target' does not exist on type 'string'“字符串”类型上不存在属性“目标”
【发布时间】:2020-02-17 14:48:48
【问题描述】:

我正在 Typescript 中创建一个搜索栏,但它没有接受任何输入。我的 onChange 方法上的术语目标不断给出一个错误,

Property 'target' does not exist on type 'string'.
export default class userSearchPage extends Component <{}, { searchItem: string}>{
  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
      searchItem: ''
    };
  }

  render() {
    return (

  <div>
    <PermanentDrawerLeft></PermanentDrawerLeft>
    <div className='main-content'>
      <SearchBar
        onChange={e => {
          this.setState({searchItem: e.target.value})
        }}             

        onRequestSearch={() => console.log('onRequestSearch')}
        style={{
          margin: '0 auto',
          maxWidth: 800
        }}
      />
    </div>
  </div>
  );
}
}

我该如何解决这个问题?

【问题讨论】:

  • onChange={e =&gt; { this.setState({searchItem: e.currentTarget.value}) }}
  • 这个搜索栏是什么?你能显示代码吗?
  • @Sodhisaab 这给出了一个错误Property 'currentTarget' does not exist on type 'string'.
  • @eladBA 我已经给出了代码。我这里使用的搜索栏是一个材质 ui 组件。

标签: javascript reactjs typescript material-ui


【解决方案1】:

您的回调onChange 似乎已经是一个字符串。所以你可以直接使用它,例如

onChange={e => this.setState({searchItem: e}) }  

【讨论】:

  • 你的意思是像这样onChange= {() =&gt; this.setState({searchItem: e})} 或onChange= {this.setState({searchItem: e})}它们都不起作用
  • @x89 你只需要替换你的setState...我为你编辑了答案
  • 现在它编译没有给出错误但我的搜索栏仍然不允许我输入任何内容!
  • 因为它是受控输入。您需要设置 value 例如value={this.state.searchItem}
【解决方案2】:

我搜索了您的 SearchBar 材料 ui,在文档中您可以看到 onChange 不返回事件,而是在您键入时返回实际值。这是一个字符串......因此错误。

如果您使用 TypeScript 来实际使用类型,我也会建议您。

所以例如你的 onChange 应该是这样的

onChange={value: string =&gt; this.setState({searchItem: value}) }

【讨论】:

    猜你喜欢
    • 2021-11-27
    • 1970-01-01
    • 2019-08-25
    • 2020-12-16
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 2019-08-27
    • 1970-01-01
    相关资源
    最近更新 更多