用户单击输入时如何使输入聚焦?

问题描述 投票:0回答:2

我已经尝试在react.js中创建一个搜索输入组件。在此组件中,我想当用户单击搜索图标时,输入焦点及其宽度通过css3 transition属性增加。这是我的代码的一部分:

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

以及我组件的手写笔代码

.news-search-v2
   width 10px
   transition: ease 0.5s all
   &:focus
      border-bottom solid 1px #5f6368
      width 300px
javascript css reactjs stylus
2个回答
1
投票

向输入声明名称属性,并将图标包装在标签元素中,并为其提供“用于”属性,其值将等于输入名称:Reason

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

为了使它发挥作用。使用“ htmlFor”代替“ for”:Reason


0
投票

[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>
      </>
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.