为什么无法读取未定义错误的属性?

发布于 2025-02-06 21:23:04 字数 1077 浏览 1 评论 0原文

我有一个React应用程序,我应该在其中从API端点获得用户:< reqres.in>。

我应该在主页上返回与从API获取用户的用户数量一样多的按钮。

另外,我被限制在所有按钮上不添加事件侦听器,而只需将一个侦听器添加到包装器中的按钮即可。相同的代码是:

const ButtonContainer = ({ users }) => {
    // const navigate=useNavigate();
    const wrapper = document.getElementById('wrapper');
    wrapper.addEventListener('click', (event) => {
        const isButton = event.target.nodeName === 'BUTTON';
        if (!isButton) {
            return;
        }
        // navigate(`/singleuser/${event.target.id}`);
    })

    return (
        <div id='wrapper'>
            {
                users.map((user, idx) => {
                    return (
                        <button key={idx} id={idx}>
                            User {idx}
                        </button>
                    )
                })
            }
        </div>
    )
}

export default ButtonContainer

用户是从API中获得的用户数组。

但是我遇到了错误:

Cannot read properties of null (reading 'addEventListener')

我该怎么办?

I have a react app in which I am supposed to get users from an API endpoint: <reqres.in>.

I am supposed to return as many buttons on the homepage as the number of users I get on fetching the users from the API.

Also I am constrained not to add event listeners to all buttons and just add one listener to the wrapper for the buttons. The code for the same is:

const ButtonContainer = ({ users }) => {
    // const navigate=useNavigate();
    const wrapper = document.getElementById('wrapper');
    wrapper.addEventListener('click', (event) => {
        const isButton = event.target.nodeName === 'BUTTON';
        if (!isButton) {
            return;
        }
        // navigate(`/singleuser/${event.target.id}`);
    })

    return (
        <div id='wrapper'>
            {
                users.map((user, idx) => {
                    return (
                        <button key={idx} id={idx}>
                            User {idx}
                        </button>
                    )
                })
            }
        </div>
    )
}

export default ButtonContainer

users is the array of users Im getting from the API.

However I am getting the error:

Cannot read properties of null (reading 'addEventListener')

What should I do?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

勿挽旧人 2025-02-13 21:23:04

使用带有React的本机方法不会为您提供所需的结果,因为React具有自己的管理DOM的方式。

OnClick添加到包装器元素中:

<div onClick={handleClick}>

然后让handleclick处理该事件。

function Example({ users }) {

  function handleClick(e) {

    // Because we're using event delegation [1]
    // check if the clicked element was a user button
    if (e.target.matches('button.user')) {

      // Extract the id from its dataset,
      // and log it
      const { id } = e.target.dataset;
      console.log(`User: ${id}`);
    }
  }

  return (
    <div onClick={handleClick}>
      {users.map(user => {
        return (
          <button
            key={user.id}
            className="user"
            data-id={user.id}
          >User: {user.id}
          </button>
        );
      })}
    </div>
  );

}

const users = [{ id: 1 }, { id: 2 }, { id: 3 }];

ReactDOM.render(
  <Example users={users} />,
  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>

Using native DOM methods with React won't give you the result you want as React has its own way of managing the DOM.

Add an onClick to your wrapper element:

<div onClick={handleClick}>

and then have handleClick deal with the event.

function Example({ users }) {

  function handleClick(e) {

    // Because we're using event delegation [1]
    // check if the clicked element was a user button
    if (e.target.matches('button.user')) {

      // Extract the id from its dataset,
      // and log it
      const { id } = e.target.dataset;
      console.log(`User: ${id}`);
    }
  }

  return (
    <div onClick={handleClick}>
      {users.map(user => {
        return (
          <button
            key={user.id}
            className="user"
            data-id={user.id}
          >User: {user.id}
          </button>
        );
      })}
    </div>
  );

}

const users = [{ id: 1 }, { id: 2 }, { id: 3 }];

ReactDOM.render(
  <Example users={users} />,
  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>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文