javascript this.textInput.focus 不是一个函数 - React
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46484640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
this.textInput.focus is not a function - React
提问by Dlike
I have FormControl for password input with icon that toggles the mask, so u cant see the characters you are inputting. But whenever I toggle this mask I also want to re-focus the input field.
我有用于密码输入的 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}
/>
... I use this method to focus:
...我用这个方法来聚焦:
handleToggleInputMode() {
let newMaskEnabled = !this.state.maskEnabled;
this.setState({maskEnabled: newMaskEnabled});
this.textInput.focus();
}
But i keep getting error
但我不断收到错误
Uncaught TypeError: this.textInput.focus is not a function
未捕获的类型错误:this.textInput.focus 不是函数
So i tried to put it in ComponentDidMount but then the whole componend stopped responding (didnt accept any char I typed in). What am i missing?
所以我试图将它放在 ComponentDidMount 中,但随后整个组件停止响应(不接受我输入的任何字符)。我错过了什么?
回答by Jigar Shah
Please check working demo
请检查工作演示
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>
Edit
编辑
for FormControl you should use inputRefas per documentation
对于 FormControl,您应该按照文档使用inputRef
<FormControl inputRef={ref => { this.input = ref; }} />
回答by Balsa Bojic
According to the current docs (https://reactjs.org/docs/refs-and-the-dom.html), use:
根据当前文档(https://reactjs.org/docs/refs-and-the-dom.html),使用:
this.textInput.current.focus();
So it should reference to the currentto get the DOM node.
所以它应该引用 来current获取 DOM 节点。

