Sam*_*Sam 1 javascript reactjs
将此绑定到我的 addTimes 函数时,我收到一条错误消息:无法读取未定义的属性“绑定”。
我在 ReactjJS 和 Webpack 中构建。最近我遇到了另一个问题,人们建议:
this.addTimes = this.addTimes.bind(this);
Run Code Online (Sandbox Code Playgroud)
请参阅:无法读取未定义 ReactJS 的属性“setState”
class Settings extends React.Component {
constructor(props) {
super(props);
this.state = {
times: []
};
}
render(){
this.addTimes = this.addTimes.bind(this);
Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
var currentTicked = [];
var times =[]
function addTimes(id){
var index = times.indexOf(id);
if (!times.includes(id)) {
$("input:checkbox[name=time]:checked").each(function(){
currentTicked.push($(this).val());
times = times.concat(currentTicked)
times = jQuery.unique(times);
currentTicked = [];
});
} else if(times.includes(id)){
times = times.remove(id);
}
console.log(times);
this.setState = {
thims: times
}
}
Run Code Online (Sandbox Code Playgroud)
为了能够在构造函数中绑定addTimes到this,addTimes必须是您的类上的一个方法,而不仅仅是渲染方法中的一个函数。
class Settings extends React.Component {
constructor(props) {
super(props);
this.state = {
times: []
};
this.addTimes = this.addTimes.bind(this);
}
addTimes(id) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想addTimes在 render 方法中创建,你可以绑定this到那里的函数:
function addTimes(id) {
// ...
}.bind(this);
Run Code Online (Sandbox Code Playgroud)
或者你可以把它变成一个箭头函数:
const addTimes = (id) => {
// ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6890 次 |
| 最近记录: |