How to autofocus an input field in semantic-ui-react?

时光毁灭记忆、已成空白 提交于 2019-11-28 07:36:50

问题


I'm having a difficult time autofocusing an input field with semantic-ui-react. The documentation doesn't seem to include an autoFocus prop and the focus prop doesn't place the cursor inside the input field as would be expected.

<Form onSubmit={this.handleFormSubmit}>
  <Form.Field>
    <Form.Input
      onChange={e => this.setState({ username: e.target.value })}
      placeholder='Enter your username'
      fluid />
  </Form.Field>
</Form>

EDIT: This code works:

<Form onSubmit={this.handleFormSubmit}>
  <Form.Input
    onChange={e => this.setState({ username: e.target.value })}
    placeholder="Enter your username"
    autoFocus
    fluid />
</Form>

回答1:


The focus prop is purely to add a focus effect on the input's appareance, it does not actually set the focus.

Any props unused by Semantic are passed down to the DOM element, so if you set an autoFocus prop, it should go down to the input.

However, as explained in the Form documentation:

Form.Input

Sugar for <Form.Field control={Input} />.

So your code should rather be:

const yourForm = (
  <Form onSubmit={this.handleFormSubmit}>
    <Form.Input
      onChange={e => this.setState({ username: e.target.value })}
      onSelect={() => this.setState({ usernameErr: false })}
      placeholder="Enter your username"
      error={usernameErr}
      iconPosition="left"
      name="username"
      size="large"
      icon="user"
      fluid
      autoFocus
    />
  </Form>
)

Note that this only works if you want the focus to happen right when the wrapper component is mounted. If you want to focus the input after it has been mounted, you have to use a ref and call the focus() method on it, just as showed in the documentation, like so:

class InputExampleRefFocus extends Component {
  handleRef = (c) => {
    this.inputRef = c
  }

  focus = () => {
    this.inputRef.focus()
  }

  render() {
    return (
      <div>
        <Button content='focus' onClick={this.focus} />
        <Input ref={this.handleRef} placeholder='Search...' />
      </div>
    )
  }
}

Hope that helps!




回答2:


I would have assumed that semantic UI would pass all unknown props to the root element, the input. So if it does, you should be able to add the autoFocus attribute to it, if not, you will have to control which input is being focused in your state.

<Input placeholder='Search...' focus={this.state.focusedElement === "search"}/>


来源:https://stackoverflow.com/questions/49177857/how-to-autofocus-an-input-field-in-semantic-ui-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!