[英]Uncaught Reference Error when trying to pass a function through a button in JavaScript?
[英]Uncaught Reference Error xyz is not defined when trying to pass parameters
我目前正在嘗試傳遞參數來設置當前大小的 state,具體取決於用戶當前使用的選項,因此我設置了一個 function 以及一個參數,每當觸發 onSelect 時,它都會傳遞大小的變量,但對於某些原因我得到我的 function 沒有定義,我猜它是我的語法,但我似乎無法弄清楚,這是我當前的代碼:
const updateSize = userSize = () => {
setSize(userSize);
console.log(userSize);
}
<select className="buttons form-control mb-2">
<option onSelect={updateSize("Small")}>Small</option>
<option onSelect={updateSize("Medium")}>Medium</option>
<option onSelect={updateSize("Large")}>Large</option>
</select>
而不是const updateSize = userSize = () => {
const updateSize = (userSize) => {
不要在單個選項上設置事件偵聽器,而是在<select>
標記本身上設置它。 然后獲取所選選項的文本並在游覽代碼中使用它。
HTML
<select onchange="updateSize()" className="buttons form-control mb-2" id="select">
<option>Small</option>
<option>Medium</option>
<option>Large</option>
</select>
JS
<script>
function updateSize() {
let select = document.getElementById('select');
let text = select.options[select.selectedIndex].text;
console.log(text)
}
</script>
文本值可以是小、中或大,具體取決於選擇的選項。
問題是因為我的 function 在另一個 function 內部,而我沒有注意到因此在 scope 之外。
如果您想為 const function 提供參數,請使用以下方法。
<select className="buttons form-control mb-2">
<option onSelect={()=>updateSize("Small")}>Small</option>
<option onSelect={()=>updateSize("Medium")}>Medium</option>
<option onSelect={()=>updateSize("Large")}>Large</option>
</select>
也適用於您的 updateSize function。 將參數保留在()內。
const updateSize = (userSize) => {
setSize(userSize);
console.log(userSize);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.