gpt4 book ai didi

javascript - react : how to check and uncheck a checkbox

转载 作者:行者123 更新时间:2023-12-01 02:50:02 25 4
gpt4 key购买 nike

我写了这个 React 组件:

import React from 'react';

export default class Todo extends React.Component {
constructor(props) {
super(props);

// Set initial state
this.state = {
data: props.data
}
}

changeStatus() {
// This throws: Uncaught TypeError: Cannot read property 'state' of undefined
console.log(this.state);
console.log('status changed');
}

render() {
let status = this.state.data.opened ? 'opened' : 'closed';
return (
<li className={"todo " + status} data-endpoint={this.state.data['@id']}>
<div className="status">
<input type="checkbox" checked={!this.state.data.opened} onChange={this.changeStatus}/>
</div>
<a href={window.Routing.generate('todo_list_todo_show', {account: this.props.todoList.account.id, list: this.props.todoList.id, todo: this.state.data.id}, true)}>{this.state.data.name}</a>
</li>
);
}
}

我希望根据对服务器的调用来选中和取消选中该复选框以更新数据库中的行。

不幸的是console.log()抛出异常:

Uncaught TypeError: Cannot read property 'state' of undefined

at changeStatus (Todo.jsx:20)

如何访问 state在处理状态变化的方法中?

最佳答案

在构造函数中绑定(bind) changeStatus 方法 -

constructor(props) {
super(props);

// Set initial state
this.state = {
data: props.data
}
this.changeStatus = this.changeStatus.bind(this);

}

您可以阅读为什么需要绑定(bind) here .

关于javascript - react : how to check and uncheck a checkbox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47031380/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com