如何在语义 - 反应中自动聚焦输入字段?

时间:2018-03-08 16:24:10

标签: semantic-ui-react

我很难用语义ui-react自动对焦输入字段。 documentation似乎不包含autoFocus道具,而focus道具并未将光标置于输入字段内。正如预期的那样。

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

编辑:此代码有效:

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

3 个答案:

答案 0 :(得分:12)

focus道具纯粹是为了对输入的外观添加焦点效果,它实际上并没有设定焦点。

Semantic未使用的任何道具都是passed down to the DOM element,所以如果你设置autoFocus道具,它应该归结为输入。

但是,如Form documentation中所述:

  

<强> Form.Input

     

<Form.Field control={Input} />的糖。

所以你的代码应该是:

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>
)

请注意,这仅在您希望焦点在安装包装器组件时正确发生时才有效。如果您想在安装后将输入对焦,则必须使用参考并在其上调用focus()方法,就像documentation中所示,如下所示:

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>
    )
  }
}

希望有所帮助!

答案 1 :(得分:1)

我会假设语义UI会将所有未知道具传递给根元素即输入。因此,如果确实如此,您应该能够为其添加autoFocus属性,否则,您将必须控制在您的状态中聚焦哪个输入。

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

答案 2 :(得分:1)

为了告诉输入字段焦点,您需要创建对输入字段的引用(ref),如下所示:

import React, { useState, useRef } from 'react';
import { Input, Button } from 'semantic-ui-react';

const SearchInputExample = () => {
  const [searchValue, setSearchValue] = useState('');

  // Create reference to the input field
  const searchRef = useRef(null);

  const handleSearchValueChange = event => setSearchValue(event.target.value);

  return (
    <div>
      <Input
        placeholder="Search..."
        // Assign the ref created to a ref attribute
        ref={searchRef}
        value={searchValue}
        onChange={handleSearchValueChange}
      />
      <Button
        onClick={() => {
          setSearchValue('');
          // Use the ref assigned to put the focus inside the input
          searchRef.current.focus();
        }}
      >
        Clear search (and focus)
      </Button>
    </div>
  );
};

export default SearchInputExample;

您可以详细了解useRef()钩子here

相关问题