简体   繁体   English

如何在React上获取动态引用

[英]How to get dynamic ref on React

I have an element with this ref 我有这个参考元素

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

and in a function I need to work with that ref doing something like this 在一个函数中,我需要使用该引用来做这样的事情

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

but I am getting an error 但我收到一个错误

./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');

so, which is the way to do this ? 那么,这样做的方法是什么?

${} is only valid inside template literals. ${}仅在模板文字内部有效。 this.refs.inner-player${this.props.position}; is not a template literal. 不是模板文字。

If you want to use a computed property name, you have to use bracket notation: 如果要使用计算所得的属性名称,则必须使用括号符号:

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

See Dynamically access object property using variable . 请参见使用变量动态访问对象属性

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

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