[英]React checkbox - Onchange checkbox, coming undefined for 1st time
[英]Checkbox onchange function is always undefined in React component class
我的復選框上的 onchange function 始終未定義。 我做了一個沙箱來簡化我的問題。 我嘗試在箭頭和常規 function 之間來回更改它,並將綁定保留為默認 state,而不是將其綁定到構造函數中的綁定。
import "./styles.css";
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.renderCheckboxes = this.renderCheckboxes.bind(this);
this.checkboxChange = this.checkboxChange.bind(this);
}
checkboxChange = (event) => {
console.log("CHANGED");
}
renderCheckboxes(checkboxes) {
return checkboxes.map(function (obj, idx) {
return (
<div>
<label>{obj.name}</label>
<input type="checkbox" onChange={this.checkboxChange} />
</div>
);
});
}
render() {
const cbList = [
{ name: "A", mood: "Happy" },
{ name: "B", mood: "Sad" },
{ name: "C", mood: "Mad" }
];
return <>{this.renderCheckboxes(cbList)}</>;
}
}
export default App;
您的 function 未定義,因為當您的checkboxes.map
發生時,您將丟失上下文。
renderCheckboxes(checkboxes) {
return checkboxes.map(function (obj, idx) { // here
return (
<div>
<label>{obj.name}</label>
<input type="checkbox" onChange={this.checkboxChange} />
</div>
);
});
}
您可以將 function 更改為箭頭 function,這樣您就不會丟失上下文:
renderCheckboxes(checkboxes) {
return checkboxes.map((obj, idx) => { // here
return (
<div>
<label>{obj.name}</label>
<input type="checkbox" onChange={this.checkboxChange} />
</div>
);
});
}
情況可能並非如此,但如果您需要在您的checkboxChange
調用中發送一些參數,您可以像這樣使用它:
checkboxChange = (value) => { // need to set the variable here
console.log(value);
}
renderCheckboxes(checkboxes) {
return checkboxes.map((obj, idx) => {
return (
<div>
<label>{obj.name}</label>
<input type="checkbox" onChange={() => this.checkboxChange('test')} /> <!-- so you can pass it from here -->
</div>
);
});
}
容易修復,這是因為綁定在map
function 中不起作用,就像你現在一樣。 要查看此操作,請嘗試僅渲染一個復選框,而不map
,您將看到您的復選框更改方法有效。
我建議的兩個更改:
return checkboxes.map((obj, idx) => {
...
}
onChange={() => this.checkboxChange()}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.