Ant*_*nto 3 javascript reactjs material-ui
我正在使用 ReactJS 和 Material UI 创建一个应用程序。我在 FormControl 组件内有一个输入组件。当用户单击 FormControl 时(但仍在输入组件之外),我想将焦点设置在输入组件上。如何才能实现这一目标?
我已经尝试过参考,但我无法做到这一点:
<FormControl
onClick={this.textInput.focus()}
style={{ display: 'block', cursor: 'text' }}
>
<Input
error={this.props.error}
disabled={this.props.disabled}
ref={(input) => { this.textInput = input; }}
/>
</FormControl>
Run Code Online (Sandbox Code Playgroud)
我不是很熟悉material-ui,但我认为这里有两个问题。首先,您的值不是一个函数,因此当组件被实例化时,它将在尚未定义的引用上onClick调用。focus您可以通过包装调用来解决此问题:(() => this.textInput.focus()或为其创建方法/实例属性。)
其次,将组件material-ui包装Input在withStyles高阶组件中,当您使用 时ref,它指的是被包装的组件,该组件没有方法focus。相反,您可以使用inputRefprop,它创建对实际 DOM 元素的引用input。(请参阅https://material-ui-next.com/customization/api/#internal-components)
这段代码应该可以工作:
..
<FormControl
onClick={() => this.textInput.focus()}
style={{ display: 'block', cursor: 'text' }}
>
<Input
error={this.props.error}
disabled={this.props.disabled}
inputRef={(input) => { this.textInput = input; }}
/>
</FormControl>
..
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2589 次 |
| 最近记录: |