如何在受控输入的最后一个字符后设置插入符号?

时间:2017-02-02 15:14:09

标签: reactjs

我有一个带有受控输入的React组件:



class myComponent extends Component {
  toggleFocus() {
    this.setState({
      hasFocus: !this.state.hasFocus
    })
  }
  
  componentDidUpdate() {
    if (this.state.hasFocus) {
      this.input.setSelectionRange(1000,1000)
    }
  }
  
  render() {
    return (
      <input onFocus{::this.toggleFocus}
        value={this.state.myValue}
        onChange={::this.handleOnChange}
        ref={x => {this.input = x}} />
    )
  }
}
&#13;
&#13;
&#13;

我在代码中的其他地方使用hasFocus状态变量,所以我需要onFocus处理程序。我想在组件完成渲染后设置selectionRange。我也试过在toggleFocus中做这个。

1 个答案:

答案 0 :(得分:1)

您应该在this.input.focus()之前添加setSelectionRange

使用旧React.createClass的{​​{3}}如下:

var App = React.createClass({
  getInitialState () {
    return {
      hasFocus: true,
      value: 'test'
    };
  },
  toggleFocus: function() {
    this.setState({
      hasFocus: !this.state.hasFocus
    })
  },
  onChange: function(event) {
    this.setState({
      value: event.target.value
    })
  },
  componentDidMount: function() {
    if (this.state.hasFocus) {
      this.setSelectionRange();
    }
  },
  componentDidUpdate: function() {
    if (this.state.hasFocus) {
      this.setSelectionRange();
    }
  },
  setSelectionRange: function() {
      this.input.focus();
      this.input.setSelectionRange(1000,1000);
  },
  render: function() {
    return <input onFocus={this.toggleFocus} onChange={this.onChange} value={this.state.value} ref={x => {this.input = x}}/>;
  }
});

ReactDOM.render(
  <App />,
  document.getElementById('container')
);