[英]Why does using 'key' as an object's key cause calling on object.key to return as null?
我最近制作了一個免費代碼營項目,其中涉及使用 React 制作鼓機。 我創建了一個對象數組,其中包含多個鍵:“值”對,其中包含要在整個應用程序中使用的數據。
該數組如下所示:
const sounds = [
{
key: 'Q',
id: 'heater-1',
url: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-1.mp3'
}, {
key: 'W',
id: 'heater-2',
url: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-2.mp3'
}, {
key: 'E',
id: 'heater-3',
url: 'https://s3.amazonaws.com/freecodecamp/drums/Heater-3.mp3'
}];
在代碼中,一個按鈕使用了一個函數來播放與<audio>
元素鏈接的<audio>
:
playSound(e) {
const sound = document.getElementById(this.props.key);
sound.currentTime = 0;
sound.play();
}
this.props.key
與值arr[i].key
。 當按鈕被點擊時,拋出一個錯誤,表示const sound = document.getElementById(this.props.key);
的值const sound = document.getElementById(this.props.key);
為空。
當我將對象鍵“key”更改為“keyTrigger”以便調用this.props.keyTrigger
的代碼與值arr[i].keyTrigger
,問題得到解決並且該值被正確調用,以便該按鈕按預期工作。
我只是想更好地理解為什么使用的詞的這種簡單變化會造成如此大的差異。 據我了解, Object.key 不是一種方法(如果我錯了,請糾正我); 從字面上看,這里的問題是使用“鑰匙”一詞作為鑰匙的名稱嗎?
非常感謝任何和所有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.