TypeScript报错:Property 'trim'不存在于ChangeEvent类型,求排查建议
解决Property 'trim' does not exist on type 'ChangeEvent'.ts(2339)错误
错误根源很清晰:你把SearchBox组件onChange回调的参数当成了字符串,但实际上这个参数是ChangeEvent类型的事件对象,事件对象本身没有trim()方法,所以TypeScript抛出了类型错误。
修复代码
要获取输入框的文本内容,需要从事件对象的target.value属性中提取,之后再调用trim()处理。修改后的代码如下:
<SearchBox id={'SuggestionSearchBox'} placeholder={'Search ' + this.props.searchTitle} onSearch={newValue => this.onSearch(newValue)} onChange={(event) => { const trimmedText = event.target.value.trim(); trimmedText !== '' ? this.showSuggestionCallOut() : this.hideSuggestionCallOut(); this.setState({ searchText: event.target.value }); }} />
额外检查点
如果SearchBox是你自定义的组件,需要确认它的类型定义:是不是组件的onChange回调被错误定义为传递ChangeEvent,而非直接传递输入字符串。如果组件设计初衷就是传递字符串,那要修正组件的props类型声明,把onChange的参数类型改为string。
内容的提问来源于stack exchange,提问作者Ashok
相关产品推荐
相关产品推荐

