React Bootstrap Typeahead 指定输入字段中的字符长度

React Bootstrap Typeahead specifies the length of characters in the input field

第一个问题:为什么,如果我输入一个字母,console.log (this.state.results.length)不显示我1。只有在输入两个字母后 console.log (this.state.results.length) 才显示 2.

第二个问题:我输入三个字母,然后去掉两个字母,console.log (this.state.results.length)应该显示1和显示2。同样是当我清除输入时它应该显示 0;

此处演示:https://stackblitz.com/edit/react-frleaq

class App extends Component {
  constructor() {
    super();
    this.state = {
      results: ''
    };
  }

_handleSearch = query => {
  this.setState({
    results: query
  })
}


  render() {
    console.log(this.state.results.length)
    return (
      <div>
         <AsyncTypeahead
            clearButton
            id="basic-example"
            labelKey="name"
            onSearch={this._handleSearch}
          />
      </div>
    );
  }
}

您可以使用 onInputChange 来处理文本更改,并且可以使文本保持状态。这样你就可以检查它的长度并做任何你想做的事情。

示例:

import React from "react";

import { AsyncTypeahead } from "react-bootstrap-typeahead";
import "bootstrap/dist/css/bootstrap.css";
import "react-bootstrap-typeahead/css/Typeahead.css";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      isLoading: false,
      multiple: true,
      options: [],
      selectedUsers: [],
      currentInput: ""
    };
  }

  handleSearch = query => {
    this.setState({ isLoading: true });
    fetch(
      `https://api.github.com/search/users?q=${query}+in:login&page=1&per_page=3`
    )
      .then(resp => resp.json())
      .then(({ items }) => {
        const options = items.map(i => ({
          id: i.id,
          name: i.login
        }));
        return { options };
      })
      .then(({ options }) => {
        this.setState({
          isLoading: false,
          options
        });
      });
  };

  handleChange = selectedItems => {
    this.setState({
      selectedUsers: selectedItems,
      currentInput: ""
    });
  };

  handleInputChange = input => {
    this.setState({
      currentInput: input
    });
  };

  render() {
    const { selectedUsers, isLoading, options, currentInput } = this.state;

    return (
      <div>
        <AsyncTypeahead
          clearButton
          id="basic-example"
          isLoading={isLoading}
          options={options}
          minLength={3}
          multiple
          labelKey="name"
          onSearch={query => this.handleSearch(query)}
          onChange={selectedItems => this.handleChange(selectedItems)}
          onInputChange={input => this.handleInputChange(input)}
          placeholder="Search for users"
        />
        <hr />
        <br/>
        <br/>
        <br/>
        {currentInput.length > 0 && <button>MY BUTTON</button>}
        <hr />
        Selected {selectedUsers.length} Users: <br />
        <ul>
          {selectedUsers.map(user => (
            <li key={user.id}>{user.name}</li>
          ))}
        </ul>
      </div>
    );
  }
}

export default App;