我清除data-react.js后如何在输入字段中设置光标

时间:2018-07-02 12:56:03

标签: javascript reactjs

我正在尝试清除输入字段,并使光标聚焦在同一输入字段上。我尝试使用.focus()和自动对焦功能,但仍然无法获取这些值。

resetInput = () => {
  this.setState({ search: '' });
}

render() {
  return (
    <div className="storyboard-search-box clearfix">
      <input type="text" placeholder="Search..." value={this.state.search} onChange={this.searchBoard} />
      <button className="clear-search-button">
        <img src={clearIcon} alt="clear button" title="Clear All" onClick={this.resetInput}/>
      </button>
    </div>
  );
}

2 个答案:

答案 0 :(得分:1)

您可以存储ref中的input,并在其上调用focus方法。

示例

class App extends React.Component {
  state = {
    search: ""
  };

  searchBoard = e => {
    this.setState({ search: e.target.value });
  };

  resetInput = () => {
    this.setState({ search: "" });
    this.ref.focus();
  };

  componentDidMount() {
    setTimeout(this.resetInput, 2000);
  }

  render() {
    return (
      <div>
        <input
          type="text"
          placeholder="Search..."
          value={this.state.search}
          onChange={this.searchBoard}
          ref={ref => (this.ref = ref)}
        />
      </div>
    );
  }
}

答案 1 :(得分:0)

您可以使用ref callback in React来实现。

resetInput = () => {
  this.setState({ search: '' });
  if (this.textInput) this.textInput.focus();
}

<div className="storyboard-search-box clearfix">
  <input ref={ref => { this.textInput = ref }} type="text" placeholder="Search..." value={this.state.search} onChange={this.searchBoard} />
  <button className="clear-search-button">
    <img src={clearIcon} alt="clear button" title="Clear All" onClick={this.resetInput}/>
  </button>
</div>