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

Need ref to <input> from semantic-ui-react's Form.Input - which is surrounded by divs in 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 在使用 ref='myRef'
  2. 时设置为组件
  3. ReactDOM.findDOMNode returns一个DOM ref,但是ref设置为外div(with class='field') .

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

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

当您使用 findDOMnode(通常不建议这样做)时,您又回到了标准 js,所以:

ReactDOM.findDOMNode(your ref).querySelector('input')

应该可以

Form.Input 对于包装 Input 的某些组件来说只是 shorthand。 所以在幕后:

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

与此相同:

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

semantic-ui-react supports the react ref API for Input, but make sure you are using the current ref API and not 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>