【问题标题】:Set focus in input on clicking div在单击 div 时在输入中设置焦点
【发布时间】:2021-02-25 11:09:15
【问题描述】:

我在函数组件中有以下 HTML

<div>
   <input />
<div>
<div>
   <input />
<div>
<div>
   <input />
<div>

我没有找到任何简单的方法来做到这一点......

我有一篇文章说要存储输入引用,但在这里我对如何使用 id 或其他东西存储inputref 感到困惑......

我完全迷路了,所以无法继续

请帮忙

谢谢

【问题讨论】:

    标签: reactjs focus


    【解决方案1】:

    您可以设置id 输入并使用input 专注于输入 example

    import React from "react";
    import "./styles.css";
    
    export default function App() {
    return (
    <div className="App">
      <div
        className='inputCon'
       onClick={()=>{
        const input = document.getElementById("input");
        input.focus()
      }}>
          <input 
          placeholder="click on green area"
          id="input"
           />
      </div>
    </div>
      );
    }
    

    【讨论】:

      【解决方案2】:

      您不一定需要 ref。以下代码直接连接到 click 事件,找到最近的输入子项,并专注于它。单击橙色区域中的任意位置以关注输入:

      const MyComponent = () => {
        const onClick = evt => {
          evt.target.querySelector('input').focus();
        };
        return (<div onClick={onClick}><input/></div>);
      }
      
      ReactDOM.render((<MyComponent/>), document.body);
      div {
        padding: 1em;
        background-color: coral;
      }
      <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

      【讨论】:

        【解决方案3】:

        useRef-Hook的使用在here的详细讲解。

        但基本上你创建一个 ref 并在你的 onClick 中添加调用 .focus() ,如下所示:

        function CustomTextInput(props) {
          // textInput must be declared here so the ref can refer to it
          const textInput = useRef(null);
          
          function handleClick() {
            textInput.current.focus();
          }
        
          return (
            <div>
              <input
                type="text"
                ref={textInput} />
              <input
                type="button"
                value="Focus the text input"
                onClick={handleClick}
              />
            </div>
          );
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-02-15
          • 2018-09-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-27
          相关资源
          最近更新 更多