首页 > 解决方案 > 如何在 React.js 中实现文本字段控件

问题描述

如何使用以下两个函数之一在 React.js 中实现文本字段控件,以按关键字获取标签列表。不要修改提供的功能。

function getLabels(keyword) {
    const allLabels = ['NextActions', 'Someday_Actions', 'Costco', 'Alexa'];
  const result = allLabels
    .filter(function(x) {
      return x.toLowerCase().indexOf(keyword.toLowerCase()) > -1;
    });
  return result;
}

// or this synchronous api
function getLabelsAsync(keyword) {
    const result = getLabels(keyword);
  const delay = Math.random() * 800 + 200; // delay 200~1000ms
  return new Promise(function(resolve, reject) {
    setTimeout(resolve, delay, result);
  });
}

标签: javascriptreactjs

解决方案


您必须实现一个受控组件才能做到这一点。您需要将组件状态附加到输入的值并创建一个方法来处理用户在其上输入的每个字符。

更多细节在这里:https ://reactjs.org/docs/forms.html#control-components

class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

推荐阅读