简体   繁体   English

如何添加条件以防止在React Todo App中添加空白任务?

[英]How to add if condition to prevent blank task adding in react todo app?

I have created a simple todo app here, when press enter button the task will push to an array but when add press without adding any text to the input area, still the bullet symbol will appear. 我在这里创建了一个简单的待办事项应用程序,当按Enter键时,任务将推送到一个数组,但是在不按任何文本添加到输入区域的情况下按添加键,仍然会出现项目符号。

How to prevent this by using if condition? 如何通过使用if条件来防止这种情况?

import React, { Component } from "react";

class Basictodo2 extends Component {
  constructor(props) {
    super(props);
    this.state = {
      title: "Map arrray when press the enter button ",
      input: "",
      list: []
    };
  }

  changeHandler = t => {
    this.setState({
      input: t.target.value
    });
  };

  pressEnter = e => {
    //  var l = this.state.list;
    var i = this.state.input;
    if (e.which === 13) {
      //    l.push(i)
      this.state.list.push(i);
      this.setState({
        //    list : l,
        list: this.state.list,
        input: ""
      });
      e.preventDefault();
    }
  };

  render() {
    var { title, input, list } = this.state;
    return (
      <div>
        <form>
          <h2>{title}</h2>
          <input
            onKeyDown={this.pressEnter}
            type="text"
            value={input}
            onChange={this.changeHandler}
          />

          <div>
            <ol>
              {list.map(data => {
                return <li>{data}</li>;
              })}
            </ol>
          </div>
        </form>
      </div>
    );
  }
}

export default Basictodo2;

Try using this approach 尝试使用这种方法

if i is not null then only this will execute 如果我不为空,那么只有这将执行

var i = this.state.input;
if(i){//then do something

  if (e.which === 13) {
  //    l.push(i)
  this.state.list.push(i);
  }
}

If you don't wont to empty values to be submitted you should make the field as required by adding required attribute to the input field. 如果您不想清空要提交的值,则应通过在输入字段中添加required属性来使字段成为必填字段。

You can add if condition to check if value is not null before pushing to array like: 您可以添加if条件,以在推入数组之前检查value是否不为null,例如:

if(i) {
  // code to push to array
}

You can check i to see if it contains anything. 您可以检查i是否包含任何东西。 Like this 像这样

   if (e.which === 13) {       
      if (i) {
        const list = [...this.state.list, i]; 

        this.setState({
          list,
          input: ""
        });
      }

      e.preventDefault();
    }

So on enter you check if i is not empty (empty strings are falsy ), and then you add it to your state. 因此,在enter请检查i是否不为空(空字符串为falsy ),然后将其添加到您的状态。 You prevent default either case so you don't refresh the page on empty input submit. 您可以防止出现默认情况,因此在空输入提交时不会刷新页面。

See this codesanbox for details: https://codesandbox.io/s/14jy6jmm04 有关详细信息,请参见此代码sanbox: https ://codesandbox.io/s/14jy6jmm04

First of all, you have a major mistake in your code, you are modifying the state without the setState() function. 首先,您的代码中有一个重大错误,您正在修改状态而不使用setState()函数。 So delete this line of code: 因此,删除以下代码行:

this.state.list.push(i);

Next you need to retrieve the value of the input and check if it has a falsey value(0, empty string, null). 接下来,您需要检索输入的值,并检查它是否具有假值(0,空字符串,null)。 If it does, you prevent the default behavior and return from the function. 如果是这样,您将阻止默认行为并从函数返回。 You can retrieve the value from the e.target.value 您可以从e.target.value检索值

pressEnter = e => {
   var i = this.state.input;
    let value = e.target.value;
    if (e.which === 13) {
      if (!value) {
        e.preventDefault();
        return;
     }

After that you need to create a new array which will include the new input and update the state. 之后,您需要创建一个新数组 ,其中将包括新输入并更新状态。

  this.setState({
    //    list : l,
    list: [...this.state.list, value], // this is a new array
    input: ""
  });

In the end you will also need to add a unique key to the 'ul' elements. 最后,您还需要向'ul'元素添加唯一键。 You can use the index of the element in the list. 您可以使用列表中元素的索引。

  {list.map((data, index) => {
    return <li key={index}>data</li>;
  })}

Here is a link to the working code: 这是工作代码的链接:

https://codesandbox.io/s/5y0747y7yp https://codesandbox.io/s/5y0747y7yp

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

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