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

问题描述 投票:0回答:1

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

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属性,以及必须进行哪些更改才能使其正常工作。

reactjs bootstrap-typeahead react-bootstrap-typeahead
1个回答
0
投票

这是一个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)}
      />
    );
  }
}

Refs and the DOM

© www.soinside.com 2019 - 2024. All rights reserved.