【问题标题】:Why do I receive null when i pass this id?为什么当我传递这个 id 时会收到 null ?
【发布时间】:2022-01-26 05:53:58
【问题描述】:
import React from "react";
import MailIcon from "@material-ui/icons/Mail";

export default function App() {
  return (
    <div className="App">
      Pass: <input type="password" id="pass"/>
      <MailIcon onClick={showPass("pass")}/>
    </div>
  );
  function showPass(e)
  {
    console.log(e);
    var pass = document.getElementById(e);
    console.log(pass);
    if(pass.type === "password")
    {
      pass.type="text";
    }
    else
    {
      pass.type ="password";
    }
  }
}

我正在调用一个简单的函数来将字段类型更改为文本,但我不知道为什么它会显示此错误

Error-page

Console-log

当我在控制台记录 e 时,它​​会显示“通过”名称,但是当我传递给 getElementById 时,它会转换为 null。

【问题讨论】:

    标签: javascript html reactjs dom ecmascript-6


    【解决方案1】:

    你只需要实现这样的功能: onClick={() =&gt; showPass("pass")}

    【讨论】:

      【解决方案2】:

      onClick={showPass("pass")} 更改为onClick={()=&gt;showPass("pass")}

      【讨论】:

      • 好的,感谢您的帮助,我们将进行必要的更改!
      【解决方案3】:

      而不是使用原生 DOM 方法 you need to start thinking in React, and use state。然后,您可以单击该图标调用一个函数来更新 type 状态(最初设置为“密码”),该状态将反映在新的渲染中。

      const { useState } = React;
      
      function Example() {
      
        // Initialise the state
        const  [type, setType] = useState('password');
      
        // Set the new state when the main icon is clicked
        function changeType() {
          const newType = type === 'password' ? 'text' : 'password';
          setType(newType);
        }
      
        // Capitalise the label
        function capitalise(str) {
          return `${str[0].toUpperCase()}${str.substr(1, str.length)}`;
        }
      
        return (
          <div>
            {capitalise(type)}: <input type={type} />
            <button onClick={changeType}>Mail icon</button>
          </div>
        );
      
      }
      
      ReactDOM.render(
        <Example />,
        document.getElementById('react')
      );
      <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
      <div id="react"></div>

      【讨论】:

      • Ok..noted 会做同样的改变
      【解决方案4】:

      您的代码有多个错误:

      1- 不要在反应中使用 getElementById

      2- 必须使用 from e.target 而不是 e 来引用元素。

      1,2 => var pass = e.target; .

      3- 即便如此,在你的If中,pass.type为空!因为MailIcon没有type属性。(输入标签有type属性)

      【讨论】:

        猜你喜欢
        • 2022-01-23
        • 2020-12-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-24
        • 2018-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多