this.textInput.focus不是函数 - React

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

我有FormControl用于密码输入,带有切换掩码的图标,因此你无法看到你输入的字符。但每当我切换这个掩码时,我也想重新聚焦输入字段。

<FormGroup
    className="input-text input-text--password"
    controlId={id}
    validationState={submitFailed && touched && error ? 'error' : validationState}
  >

    <FormControl
      {...input}
      disabled={disabled}
      className="input-text__input"
      autoFocus={autoFocus}
      type={maskEnabled ? 'password' : 'input'}
      onChange={this.handleFormControlChange}
      maxLength={maxLength}
      ref = { ref => this.textInput = ref }
    />
    <div
        className={'input-text__button ' + (maskEnabled ? 'mask-enabled' : 'mask-disabled')}
        onClick={this.handleToggleInputMode}
    />

...我使用这种方法来关注:

handleToggleInputMode() {
  let newMaskEnabled = !this.state.maskEnabled;
  this.setState({maskEnabled: newMaskEnabled});
  this.textInput.focus();
}

但我不断收到错误

未捕获的TypeError:this.textInput.focus不是函数

所以我试着将它放在ComponentDidMount中,然后整个组件停止响应(没有接受我输入的任何字符)。我错过了什么?

javascript jquery reactjs
1个回答
2
投票

请查看工作演示

 class App extends React.Component {
  componentDidMount() {
    this.textInput.focus();
  }
  render() {
    return (
      <div>
        <div>
          <input
            defaultValue="It will not focus"
          />
        </div>
        <div>
          <input
            ref={(input) => { this.textInput = input; }}
            defaultValue="with focus"
          />
        </div>
      </div>
    );
  }
}
    
ReactDOM.render(<App />, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.js"></script>
<div id="app"></div>

编辑

对于FormControl,您应该根据inputRef使用documentation

<FormControl inputRef={ref => { this.input = ref; }} />
© www.soinside.com 2019 - 2024. All rights reserved.