【问题标题】:Using function param in this.refs [duplicate]在 this.refs 中使用函数参数 [重复]
【发布时间】:2018-05-04 22:02:20
【问题描述】:

我意识到这甚至可能不是 React 问题,只是我对初学者感到困惑,但无论如何我都会在这里问问题,因为我认为我不理解某些东西。

我想创建一个播放声音 onClick 事件的函数。

假设我在渲染中有 2 个音频标签:

<audio ref="jammed" src={jammedSound}></audio>
<audio ref="budge" src={budgeSound}></audio>

函数本身看起来像这样:

playSound(soundName){
  this.refs.soundName.play();
}

当我通过playSound('jammed')playSound('budge') 时它不起作用,我试图将其转换为字符串以绝望,我在soundName 上使用大括号和括号,什么都没有。我知道这可能是我不理解的 JS 问题,我将不胜感激

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    正确的语法应该是

    this.refs[soundName].play()
    

    虽然不确定 React。

    更多信息:https://www.w3schools.com/js/js_properties.asp

    【讨论】:

    • 它可以工作。我正在尝试 this.refs.[soundName].play(),我不知道你必须在括号前删除点。谢谢。
    • 如果满意,请接受答案。
    【解决方案2】:

    请注意using string literals as refs is deprecated

    改为使用函数式引用:

    <audio ref={(el) => this.jammedRef = el} src={jammedSound}></audio>
    <audio ref={(el) => this.budgeRef = el} src={budgeSound}></audio>
    

    函数本身看起来像这样:

    playSound(soundName){
      this[`${soundName}Ref`].play();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-21
      • 2020-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-19
      • 2020-04-26
      相关资源
      最近更新 更多