Javascript “如何改变”;“未完成”;至;“完成”;
我正在学习如何反应。我有个问题。我不能做不做的事。我想请求帮助。如果不难的话,我想举一个如何实现这一点的例子。如果我有错误,对不起。我英语不好Javascript “如何改变”;“未完成”;至;“完成”;,javascript,reactjs,Javascript,Reactjs,我正在学习如何反应。我有个问题。我不能做不做的事。我想请求帮助。如果不难的话,我想举一个如何实现这一点的例子。如果我有错误,对不起。我英语不好 类ToDoList扩展了React.Component{ 建造师(道具){ 超级(道具) 此.state={ 已完成:正确 } this.handleClick=this.handleClick.bind(this); } 渲染(){ const{items}=this.props 返回( {items.map(item=>( {item.id} {i
类ToDoList扩展了React.Component{
建造师(道具){
超级(道具)
此.state={
已完成:正确
}
this.handleClick=this.handleClick.bind(this);
}
渲染(){
const{items}=this.props
返回(
{items.map(item=>(
{item.id}
{item.text}
{item.date}
{this.state.Сcompleted?'Done':'notdone'}
✓;
))}
)
}
handleClick(){
console.log('--','completed')
//这是我的国家({
//已完成:!this.state.completed
// })
if(this.state.completed=true){
this.state.completed=false
}
}
}
不要将值直接分配给状态属性。改用
setState()
您的处理程序函数可以是:
handleClick = () => { // arrow functions are bound by default
console.log('---', 'completed');
this.setState({ completed: !this.state.completed });
}
只需在单击按钮时切换状态
this.setState(prevState => ({completed: !prevState.completed}))
编辑:
我认为这里的问题还不清楚
OP有一个项目数组
,他只想将完成
或未完成
设置为单击的项目
注释后的代码可以工作,但它会更改每个项目的状态,这不是OP想要的。要解决此问题,您需要为每个项目设置一个属性
completed
,并且只更新项目的属性。更正此.state.completed
,因为您的c in completed具有不同的字体
class ToDoList extends React.Component {
constructor(props) {
super(props)
this.state = {
completed: true
}
}
handleClick=()=> {
this.setState(prevState=>({completed:!prevState.completed}))
}
render () {
const { items} = this.props
const { completed } = this.state;
return (
<table>
{items.map(item => (
<tr className="hr">
<td className="col1">{item.id}</td>
<td className="col2">{item.text}</td>
<td className="col3">{item.date}</td>
<td className="col4">{completed ? 'Done' : 'Not Done'}</td>
<td className="col5"><button onClick ={ this.handleClick }className="btn btn-xs btn-success img-circle">✓</button></td>
</tr>
))}
</table>
)
}
}
类ToDoList扩展了React.Component{
建造师(道具){
超级(道具)
此.state={
已完成:正确
}
}
handleClick=()=>{
this.setState(prevState=>({completed:!prevState.completed}))
}
渲染(){
const{items}=this.props
const{completed}=this.state;
返回(
{items.map(item=>(
{item.id}
{item.text}
{item.date}
{已完成?'Done':'notdone'}
✓;
))}
)
}
}
1)
不能像这样直接更改状态:
this.sate.completed = !this.state.completed
if (this.state.completed == true) {
...
}
您必须使用如下方法“this.setState”:
this.setState({completed: !this.state.completed})
2)如果sintax的“if”也是错误的,那么应该使用double“==”,如下所示:
this.sate.completed = !this.state.completed
if (this.state.completed == true) {
...
}
3)您应该使用箭头功能:
handleClick = () => {
...
}
否则,您需要调用以下函数:
this.handleClick.bind(this)
在Django中更新状态时,必须使用setState。注释掉的代码不起作用吗?应该起作用。这不是问题的具体原因,但您对所有项目都只执行一步。。因此,一旦您将一个标记为完成,所有项目都将同时更改为
完成
或未完成
。你需要一个双等号==>如果(this.state.completed==true)我做了但失败了在你的答案中添加注释,不要发布纯代码。我做了但失败了非常感谢你应该使用双等号(=)来表示你的情况