how react programmatically focus input

前端 未结 6 2067
滥情空心
滥情空心 2020-12-15 03:01

I\'m trying to implement a very simple use case, a UI feature, where:

  1. There is a label with some content in it
  2. If clicked, a text input replaces it wi
相关标签:
6条回答
  • 2020-12-15 03:30

    The way you have used refs is not the most preferred way or else its not the best practice anymore . try some thing like this

    class MyClass extends React.Component {
      constructor(props) {
        super(props);
        this.focus = this.focus.bind(this);
      }
    
      focus() {
        this.textInput.current.focus();
      }
    
      render() {
    
        return (
          <div>
            <input
              type="text"
              ref={(input) => { this.textInput = input; }} />
            <input
              type="button"
              value="Set Focus"
              onClick={this.focus}
            />
          </div>
        );
      }
    }
    

    Update
    From React 16.3 upwards you can use the React.createRef() API

    class MyClass extends React.Component {
      constructor(props) {
        super(props);
        // create a ref to store the textInput DOM element
        this.textInput = React.createRef();
        this.focus = this.focus.bind(this);
      }
    
      focus() {
        // Explicitly focus the text input using the raw DOM API
        // Note: we're accessing "current" to get the DOM node
        this.textInput.current.focus();
      }
    
      render() {
        // tell React that we want to associate the <input> ref
        // with the `textInput` that we created in the constructor
        return (
          <div>
            <input
              type="text"
              ref={this.textInput} />
            <input
              type="button"
              value="Set Focus"
              onClick={this.focus}
            />
          </div>
        );
      }
    }
    
    0 讨论(0)
  • 2020-12-15 03:33

    @BenCarp's answer in typescript

    Pass the inputRef to an input and just call setFocus to set the focus to it.

    export const useInputFocus = (): [MutableRefObject<HTMLInputElement | undefined>, () => void] => {
      const inputRef = useRef<HTMLInputElement>();
      const setFocus = (): void => {
        const currentEl = inputRef.current;
        if (currentEl) {
          currentEl.focus();
        }
      };
      return [inputRef, setFocus];
    };
    
    0 讨论(0)
  • 2020-12-15 03:37

    In addition to the previous answers, I've added setTimeout to make it work

    handleClick() {
    
    
        if (this.searchInput) {
            setTimeout(() => {
    
                this.searchInput.focus();
    
            }, 100);
        }
    }
    

    where searchInput is the jsx ref of the input

    <input
          type="text"
          name="searchText"
          ref={(input) => { this.searchInput = input; }}
          placeholder="Search" />
    

    and the handleClick() is an onClick handler to any element

    0 讨论(0)
  • 2020-12-15 03:40

    Use componentDidUpdate method to every time update the component

    componentDidUpdate(prevProps, prevState) {
         this.input.focus();
    }
    
    0 讨论(0)
  • 2020-12-15 03:52

    Just add autofocus attribute to the input. (of course in JSX it is autoFocus)

    <input autoFocus ...
    
    0 讨论(0)
  • 2020-12-15 03:52

    useFocus hook

    // General Focus Hook
    const useFocus = (initialFocus = false, id = "") => {
        const [focus, setFocus] = useState(initialFocus)
        const setFocusWithTrueDefault = (param) => setFocus(isBoolean(param)? param : true)
        return ([
            setFocusWithTrueDefault, {
                autoFocus: focus,
                key: `${id}${focus}`,
                onFocus: () => setFocus(true),
                onBlur: () => setFocus(false),
            },
        ])
    }
    
    
    const FocusDemo = () => {
    
        const [labelStr, setLabelStr] = useState("Your initial Value")
        const [setFocus, focusProps] = useFocus(true)
    
        return (
            <> {/* React.Fragment */}
                <input
                    onChange={(e)=> setLabelStr(e.target.value)}
                    value={labelStr}
                    {...focusProps}
                />
                <h3 onClick={setFocus}>{labelStr}</h3>
            </>
        )
    
    }
    

    For a more complete demo [click here][1].

    0 讨论(0)
提交回复
热议问题