javascript - 需要从 semantic-ui-react Form.Input 引用 <input> - 在 React 中被 div 包围

标签 javascript reactjs semantic-ui-react

我正在使用 semantic-ui-react 的 Form.Input,它将输入包装在两个 div 中。

这意味着,

<Form.Input type='password' name='password' id='loginPassword'></Form.Input>

渲染如下:

<div class='field'>
  <div class='ui fluid action left icon input'>
   <input type='password' name='password' id='loginPassword' ...>
   <button ...>
  </div>
</div>

我想获得 <input/> 的引用元素,以便我可以调用 focus()。

  1. 当使用 ref='myRef' 时,我的 ref 被设置为组件
  2. ReactDOM.findDOMNode 返回一个 DOM ref,但 ref 设置为外部 div(class='field')。

如何获取 <input/> 的引用元素?

顺便说一句,我正在使用 redux,尽管我认为这不重要

最佳答案

Form.Input 只是一个 shorthand对于一些包装了 Input 的组件。 所以在幕后:

<Form.Input label='Enter Password' type='password' />

与此相同:

<Form.Field>
  <label>Enter Password</label>
  <Input type='password' />
</Form.Field>

语义用户界面 react supports the react ref API对于 Input,但请确保您使用的是 current ref API而不是 the old one :

<Input ref={ref => this.input = ref} />

运行示例:

const { Input, Button } = semanticUIReact; // import

class App extends React.Component {
  onClick = () => this.input.focus();
  render() {
    return (
      <div>
        <Input ref={ref => this.input = ref} />
        <Button onClick={this.onClick}>Focus</Button>
      </div>
    );
  }
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/semantic-ui-react@0.78.3/dist/umd/semantic-ui-react.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.9/semantic.min.css"/>
	<div id="root"></div>

关于javascript - 需要从 semantic-ui-react Form.Input 引用 &lt;input&gt; - 在 React 中被 div 包围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49119738/

相关文章:

javascript - 如何在语义 ui 中循环 react ?

javascript - react Prop 未定义

javascript - 如何防止在密码输入字段中输入空格/空白 | ReactJs

javascript - 如果没有从 document.getElementById .setAttribute href 中选择选项,则隐藏按钮

javascript - Postman - 从 Get 请求的响应中获取最后一个 id 并将其分配给变量

javascript - 滑动条触发器不起作用(又名滑动条)

javascript - 跳过延迟对象

javascript - 使用 Next.js react onClick 事件处理程序不工作

javascript - 使 react 组件可点击

javascript - 具有多项选择限制的下拉菜单