我正在尝试使用以下代码清除函数中的输入。
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问题,您只需要先定义参考即可使用。
使用经典定义:
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();
}
handleChange(e) {
this.typeahead.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)}
/>
);
}
}