简体   繁体   English

无法在反应 js 中正确使用 Refs,无法读取未定义的属性

[英]can't use the Refs properly in react js, Cannot read property of undefined

I am very new to react and js, I have a menu and submenu, I use a list to map data, I want to write a function, so onmouseover one item in the list, if it has submenu, it will show.我对react和js很新,我有一个菜单和子菜单,我用一个列表来map数据,我想写一个function,所以onmouseover列表中的一项,如果有子菜单就会显示。 the problem is that I can't select the submenu using ref.问题是我不能 select 使用参考的子菜单。 It is just too complicated for me, any help would be much appreciated!这对我来说太复杂了,任何帮助将不胜感激! enter image description here在此处输入图像描述

 import React, { Component } from "react"; export class Menu extends Component { constructor(props) { super(props); this.liRefs = []; } showSubmenu = (e) => { // this.liRefs.current.style.display = "block"; for (var i = 0; i < this.liRefs.length; i++) { this.liRefs[i].current.style.display = "block"; } // console.log(this.liRefs[10]); }; getStyle = (e) => { e.target.style.background = "red"; }; render() { return ( <ul className="mainmenu"> {this.props.items.map((i) => i.subitems? ( <li key={i.id} onMouseOver={this.showSubmenu}> {i.icon} {i.name} <ul key={i.id} ref={(ref) => (this.liRefs[i.id] = ref)}> {i.subitems.map((item) => ( <div key={item.id} className="submenu"> {item.icon} {item.name} </div> ))} </ul> </li> ): ( <li key={i.id}> {i.icon} {i.name} {i.img} </li> ) )} </ul> ); } } export default Menu;

You are giving ref value to this. liRefs[i.id]this. liRefs[i.id] this. liRefs[i.id] and accessing through this. liRefs[i] this. liRefs[i.id]并通过this. liRefs[i] this. liRefs[i] so that both are the different change your code as below: this. liRefs[i]这样两者都是不同的,更改您的代码如下:

{this.props.items.map((i,index) =>
          i.subitems ? (
            <li key={i.id} onMouseOver={this.showSubmenu}>
              {i.icon}
              {i.name}
              <ul key={i.id} ref={(ref) => (this.liRefs[i.id] = ref)}>
                {i.subitems.map((item) => (
                  <div key={item.id} className="submenu">
                    {item.icon}
                    {item.name}
                  </div>
                ))}
              </ul>
            </li>
          ) : (
            <li key={i.id}>
              {i.icon}
              {i.name}
              {i.img}
            </li>
          )
        )}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM