繁体   English   中英

如何将“未完成”更改为“完成”

[英]How to change “Not Done” to “Done”

我正在学习React。 我有问题。 我无法将“未完成”设置为“完成”。 我想寻求帮助。 如果不难,我想举个例子来说明如何实现。 如果我有错误,对不起。 我英语不好。

在此处输入图片说明

class ToDoList extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
        completed: true
    }
    this.handleClick = this.handleClick.bind(this);
  }

  render () {
  const { items} = this.props
  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">{this.state.сompleted ? 'Done' : 'Not Done'}</td>
              <td className="col5"><button onClick ={ this.handleClick }className="btn btn-xs btn-success img-circle">&#x2713;</button></td>
            </tr>
          ))}
    </table>
  )
  }

    handleClick() {
      console.log('---', 'completed')
    //   this.setState({
    //       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 });
}
if (this.state.completed = true) {
      this.setState({completed:false })
    }

单击按钮时只需切换状态

this.setState(prevState => ({completed: !prevState.completed}))

编辑:

我认为问题还不清楚。

OP具有一系列items ,他想将Done或“ Not Done仅设置为单击的项目。

注释的代码有效,但是它更改了每个项目的状态,这不是OP想要的。 要解决此问题,您需要为每个项目completed一个属性,并仅更新该项目的属性。

更正您的this.state.completed因为您完成的c具有不同的字体

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">&#x2713;</button></td>
        </tr>
      ))}
</table>
  )
  }
} 

1)您不能像这样直接更改状态:

this.sate.completed = !this.state.completed

您必须使用方法“ this.setState”,如下所示:

this.setState({completed: !this.state.completed})

2) “如果” sintax也是错误的,则应使用双“ ==”,如下所示:

if (this.state.completed == true) {
  ...
}

3)您应该使用箭头功能:

handleClick = () => {
  ...

}

否则,您需要像这样调用函数:

this.handleClick.bind(this)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM