如何使用React bootstrap typeahead清除函数中的输入



我正在尝试使用以下代码清除函数中的输入。

import {Typeahead} from 'react-bootstrap-typeahead';
type requestState={
value:string[]
}
class Data extends Component<{},requestState> {
constructor(props){  
super(props);  
this.state = {  
value: [],
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.typeahead.getInstance().clear();
}
render() {
return(
<Typeahead
ref={(ref) => this.typeahead = ref}
id="data"
labelKey="data"
multiple={true}
options={this.state.values}
placeholder="Choose a data.."
onChange={(e) => this.handleChange(e)}
/>
);
}
}
export default Data;

当我尝试使用此代码一次清除输入时,我会收到以下错误:"类型"Data"上不存在属性"typeahead"。

有人能帮我如何定义typeahead属性,以及需要做哪些更改才能使其工作吗。

这是一个react ref问题,您只需要先定义ref即可使用。

使用经典定义:

class Data extends Component<{},requestState> {
constructor(props){  
super(props);  
this.state = {  
value: [],
}
this.handleChange = this.handleChange.bind(this);
this.typeahead = null;
}
handleChange(e) {
this.typeahead.getInstance().clear();
}
render() {
return(
<Typeahead
ref={(ref) => this.typeahead = ref}
id="data"
labelKey="data"
multiple={true}
options={this.state.values}
placeholder="Choose a data.."
onChange={(e) => this.handleChange(e)}
/>
);
}
}

使用React.createRef

class Data extends Component<{},requestState> {
constructor(props){  
super(props);  
this.state = {  
value: [],
}
this.handleChange = this.handleChange.bind(this);
this.typeahead = createRef<Typeahead>();
}
handleChange(e) {
this.typeahead.current.getInstance().clear();
}
render() {
return(
<Typeahead
ref={this.typeahead}
id="data"
labelKey="data"
multiple={true}
options={this.state.values}
placeholder="Choose a data.."
onChange={(e) => this.handleChange(e)}
/>
);
}
}

参考文献和DOM

这些更改在typescript中对我有效,可以使用React Bootstrap Typeahead 清除输入

import React, { Component } from 'react';
import {Typeahead} from 'react-bootstrap-typeahead';
class Data extends Component<{},requestState> {
typeahead = React.createRef<Typeahead>();
constructor(props){  
super(props);  
this.state = {  
value: [],
}
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.typeahead.current.state.selected= []
}
render() {
return(
<Typeahead
ref={this.typeahead}
id="data"
labelKey="data"
multiple={true}
options={this.state.values}
placeholder="Choose a data.."
onChange={(e) => this.handleChange(e)}
/>
);
}
}
export default Data;

最新更新