【问题标题】:How to use getAttribute in react?如何在反应中使用getAttribute?
【发布时间】:2018-01-23 00:55:55
【问题描述】:

我正在使用 .map 在 React 应用中创建一个小列表

{
 this.state.rooms.map((anything, indexPos) =>
   <p className='rooms'
      onClick={this.test}
         key={indexPos}>{anything.name}
   </p>
 )
}

onClick方法调用的'test'函数如下:

test = (e) => {
 alert();
}

我的问题是我应该在 alert 方法的“()”中输入什么代码来提醒点击了哪个特定房间?

了解我的构造函数的样子也可能会有所帮助:

constructor(props) {
  super(props);
  this.state = {
    rooms: [],
    display: 'none',
    newRoomName: 'New room',
    currentRoom: ''
};
  this.roomsRef = this.props.firebase.database().ref('rooms');
}

这是与 Question 关联的 git 文件的 LINK

能够提醒();然后,我单击的任何房间的“键”属性或索引或房间名称都将允许我“渲染”选定的房间。感谢您的任何建议。

【问题讨论】:

  • e.target.key 可能
  • 不,这给出了“未定义”的 Jaromanda。谢谢

标签: javascript reactjs getattribute


【解决方案1】:

您可以将单个房间传递给您的test 回调。但是我们现在有一个参数,所以你需要包装你的函数,否则你会立即调用test,这不是你想要的,你只想定义一个回调。

{
 this.state.rooms.map((room, indexPos) =>
   <p className='rooms'
      onClick={() => this.test(room)}
         key={indexPos}>{room.name}
   </p>
 )
}

现在你的回调有一个参数,你可以打印一些属性

test = (room) => {
 alert(room.name);
}

【讨论】:

  • 工作就像一个魅力!现在我必须明白为什么会这样......但是谢谢一百万,当计时器在六分钟后停止时,我会给你绿色检查。
猜你喜欢
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 2019-06-12
  • 2020-04-24
  • 2021-12-15
  • 2019-01-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多