为什么无法读取未定义错误的属性?
我有一个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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用带有React的本机方法不会为您提供所需的结果,因为React具有自己的管理DOM的方式。
将
OnClick
添加到包装器元素中:然后让
handleclick
处理该事件。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:and then have
handleClick
deal with the event.