如何通过单击从待办事项列表中删除项目?

时间:2019-11-12 19:45:24

标签: reactjs

在创建此应用程序时出现问题,请告知:

  1. 如何删除添加到列表中的项目 通过单击项目本身?

  2. 请提供有关改进此部分的建议。

创建该应用程序是为了解决我遇到的一些问题并学习该领域。

  

在此领域的任何建议或任何指导将不胜感激。

import React from "react";
import InputBar from "./InputBar";
import ListofItems from "./ListofItems";

class App extends React. Component {
  state = {
    listOfinputs: [] //name: ""
  };

  render() {
    return (
      <div className="ui segment ui container">
        <InputBar
          //name={"mocahel"}
          onSubmitPress={
            input =>
              this.setState({
                listOfinputs: [...this.state.listOfinputs, input]
                //  name: "matan"
              }) //creare new pointer to array
            //this.state.listOfinputs.push(input)
          }
        />
        <ListofItems data={this.state.listOfinputs} />
      </div>
    );
  }
}

export default App;



import React from "react";

class InputBar extends React.Component {
  state = { input: "" };

  onInputChanged = event => {
    //console.log(event)
    this.setState({ input: event.target.value });
  };

  render() {
    const { name, onSubmitPress } = this.props;
    return (
      <form
        onSubmit={event => {
          onSubmitPress(this.state.input);
          event.preventDefault();
        }}
      >
        <label>
          Name:
          <input
            type="text"
            value={this.state.input}
            onChange={event => this.onInputChanged(event)}
          />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

export default InputBar;



import React from "react";

const ListofItems = (props) => {
  const { data } = props;
  console.log(data, 'test2')
  return (
    <div className="ui segment">
      <ul>
      {data.map((input, index) =>
        <li key={index}>{input}</li>)}
        </ul>
    </div>
  );
};

export default ListofItems;


1 个答案:

答案 0 :(得分:0)

const ListofItems = (props) => {
  const { data } = props;
  console.log(data, 'test2')
  return (
    <div className="ui segment">
      <ul>
      {data.map((input, index) =>
        <a onClick={() => props.deleteItem(index)}><li key={index}>{input}</li></a>)}
       </ul>
    </div>
  );
};


class App extends React. Component {
  state = {
    listOfinputs: [] //name: ""
  };



  handleDelete(index) {
    // HERE COMES THE DELETE LOGIC FROM THE STATE WITH INDEX
  }
  render() {
    return (
      <div className="ui segment ui container">
        <InputBar
          //name={"mocahel"}
          onSubmitPress={
            input =>
              this.setState({
                listOfinputs: [...this.state.listOfinputs, input]
                //  name: "matan"
              }) //creare new pointer to array
            //this.state.listOfinputs.push(input)
          }
        />
        <ListofItems deleteItem={this.handleDelete} data={this.state.listOfinputs} />
      </div>
    );
  }
}