簡體   English   中英

當用戶單擊輸入時如何聚焦輸入?

[英]How to focus input when a user clicked on an input?

我嘗試在 react.js 中創建一個搜索輸入組件。 在這個組件中,我希望當用戶單擊搜索圖標時,輸入焦點及其寬度由 css3 過渡屬性增加。 這是我的一段代碼:

    <input className={"news-search-v2"} type="text" />
    <i className="material-icons"> search </i>

以及我的組件的手寫筆代碼

.news-search-v2
   width 0px
   transition: ease 0.5s all
   &:focus
      border-bottom solid 1px #5f6368
      width 300px

為 Input 聲明 name 屬性並將圖標包裝在 label 元素中,並為其提供“for”屬性,其值等於輸入的名稱: Reason

<input name="search" className={"news-search-v2"} type="text" />
<label for="search"><i className="material-icons"> search </i></label>

讓這個工作在反應中。 使用“htmlFor”而不是“for”:原因

Arnav Yagnik答案是正確的,但不是React解決方案。

如果您的組件是函數式組件,則可以使用useRef鈎子。

import React from 'react';

const FocusExample = () => {
  const textInput = React.useRef(null);

  const setFocus = React.useCallback(() => { textInput.current.focus() });

  return (
    <>
      <input ref={textInput} className={"news-search-v2"} type="text" />
      <i className="material-icons" onClick={setFocus}> search </i>
    </>
  );
};

或者,如果您使用基於分類的視圖,請使用createRef

import React from 'react';

class FocusExample extends React.Component {
  constructor(props) {
      super(props);

      this.textInput = React.createRef();
  }

  setFocus = () => {
    this.textInput.current.focus();
  }

  render() {
    return(
      <>
        <input ref={this.textInput} className={"news-search-v2"} type="text" />
        <i className="material-icons" onClick={this.setFocus}> search </i>
      </>
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM