如何在React上获得动态引用

How to get dynamic ref on React

本文关键字:动态 引用 React      更新时间:2023-09-26

我有一个带有此ref 的元素

ref={`inner-player${this.props.position}`}

在一个函数中,我需要和那个裁判一起做一些类似的事情

const chipBetImage = this.refs.inner-player${this.props.position};

但是我收到一个错误

./app/components/ui/PlayerSlot/index.js
Module build failed: SyntaxError: /home/marcelo/Documents/Projects/application-playerinterface/app/components/ui/PlayerSlot/index.js: Unexpected token (150:50)
  148 |       this.props.addMoney({position : this.props.position, currentBet : this.props.currentBet});
  149 |     } else {
> 150 |       const chipBetImage = this.refs.inner-player${this.props.position};
      |                                                   ^
  151 |       chipBetImage.classList.add('animated', 'pulse');

那么,该怎么做呢?

${}仅在模板文本内有效。this.refs.inner-player${this.props.position};不是模板文字。

如果你想使用计算的属性名称,你必须使用括号表示法:

this.refs[`inner-player${this.props.position}`]

请参阅使用变量动态访问对象属性。