首页 > 解决方案 > 如何将文本插入到输入中键入的列表中

问题描述

import React, { Component, createElement } from "react";

export default class TodoList extends Component {
  state = {
    todo: [],
    inputValue: "",
  };

  addTodo = () => {
    this.setState({ todo: [...this.state.todo, this.state.inputValue] });

    // I want to insert separate paragraph tags (todos from this.state.todo) into the list element here
  };

  handleKeyDown = (e) => {
    if (e.keyCode === 13) {
      if (this.state.inputValue === "") return;

      this.addTodo();
    }
  };

  handleChange = (e) => {
    this.setState({ inputValue: e.target.value });
  };

  render() {
    return (
        <div className="list"></div>
        <input
          type="text"
          className="insertTodo"
          placeholder="Add a new todo!"
          onChange={this.handleChange}
          onKeyDown={this.handleKeyDown}
          value={this.state.inputValue}
        />
    );
  }
}

我正在创建一个待办事项列表,用户在其中输入一个输入,然后将待办事项插入到divwith 类list元素中。我是 React 的新手,所以我不知道我应该采取的最佳方式。

任何帮助表示赞赏,谢谢!

标签: javascripthtmlreactjs

解决方案


您可以map将数组放在div 中,并通过将每个待办事项包装在标签.list中来呈现每个待办事项 。p我添加了一个button元素来处理该addTodo()功能。
此外,您可能希望将.listdiv 移动到输入下方。

import React, { Component, createElement } from "react";

export default class TodoList extends Component {
  state = {
    todo: [],
    inputValue: ""
  };

  addTodo = () => {
    this.setState({ todo: [...this.state.todo, this.state.inputValue] });

    // I want to insert separate paragraph tags (todos from this.state.todo) into the list element here
  };

  handleKeyDown = (e) => {
    if (e.keyCode === 13) {
      if (this.state.inputValue === "") return;

      this.addTodo();
    }
  };

  handleChange = (e) => {
    this.setState({ inputValue: e.target.value });
  };

  render() {
    return (
      <div>
        <div className="list">
          {this.state.todo.map((todo) => {
            return <p>{todo}</p>;
          })}
        </div>
        <input
          type="text"
          className="insertTodo"
          placeholder="Add a new todo!"
          onChange={this.handleChange}
          onKeyDown={this.handleKeyDown}
          value={this.state.inputValue}
        />
        <button onClick={this.addTodo}>Add Todo</button>
      </div>
    );
  }
}

Codesandbox 链接 - https://codesandbox.io/s/busy-pascal-txh55?file=/src/App.js


推荐阅读