Как добавить новый компонент к каждому входу? - PullRequest
0 голосов
/ 09 июля 2020

У меня есть форма. Когда я что-то ввожу и нажимаю «отправить», я хочу, чтобы мое приложение добавляло новый компонент, который должен включать этот ввод каждый раз, когда я нажимаю «отправить».

export default class AddForm extends Component{
    constructor(props){
        super(props);
        this.state = {
            input: '',
            obj: [],
            
        }
        this.onHandleChange = this.onHandleChange.bind(this);
        this.onHandleSubmit = this.onHandleSubmit.bind(this);
    }

    onHandleChange(e){
        this.setState({
            input: e.target.value
        });
        
    }

   onHandleSubmit(){
        this.state.obj.push(this.state.input);
        this.setState({
            input: ''
        })
   }

   

    render(){
        return(
            <div className = 'adder'>
                <h1 className = 'header'>Enter the type of tasks you need to be done:</h1>
                <div>
                <form>
                    <input className = 'board-add'  onSubmit = {this.onHandleSubmit} onChange = {this.onHandleChange} type = 'search' name = 'textarea' placeholder = 'How shall we call the board?'/>
                    <p><button className = 'cancel'>CANCEL</button>
                    <button onClick = {this.onHandleSubmit} className = 'create'>CREATE</button></p>
                </form>
                </div>
                {this.state.obj.map((item) => <TaskBoard taskType = {item} />)}
            </div> 

        );
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

1 Ответ

0 голосов
/ 09 июля 2020
   this.state.obj.push(this.state.input);

^ Это не очень хорошая практика в React. вместо этого сделайте это

  obj: [...this.state.obj, this.state.input],

Для получения дополнительной информации о ... прочтите ссылку ниже

https://medium.com/coding-at-dawn/how-to-use-the-spread-operator-in-javascript-b9e4a8b06fab

также

У вас не было пропуска value в поле ввода, поэтому вы не сможете сбросить поле после выполнения отправки.

  <input
    className="board-add"
    onSubmit={this.onHandleSubmit}
    onChange={this.onHandleChange}
    type="search"
    name="textarea"
    value={this.state.input}
    placeholder="How shall we call the board?"
  />

codeandbox

https://codesandbox.io/s/adoring-elbakyan-69hth?file= / src / App. js: 0-1459

Надеюсь, это ответит на ваш вопрос.

AddForm. js

import React from "react";
import "./styles.css";
import TaskBoard from "./Taskboard";
export default class Addform extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: "",
      arr: []
    };
    this.onHandleChange = this.onHandleChange.bind(this);
    this.onHandleSubmit = this.onHandleSubmit.bind(this);
  }

  onHandleChange(e) {
    this.setState({
      input: e.target.value
    });
  }

  onHandleSubmit(e) {
    e.preventDefault();

    this.setState({
      arr: [...this.state.arr, this.state.input],
      input: ""
    });
  }

  render() {
    console.log(this.state.arr);
    return (
      <div className="adder">
        <h1 className="header">Enter the type of tasks you need to be done:</h1>
        <div>
          <form>
            <input
              className="board-add"
              onSubmit={this.onHandleSubmit}
              onChange={this.onHandleChange}
              type="search"
              name="textarea"
              value={this.state.input}
              placeholder="How shall we call the board?"
            />
            <p>
              <button className="cancel">CANCEL</button>
              <button onClick={this.onHandleSubmit} className="create">
                CREATE
              </button>
            </p>
          </form>
        </div>
        {this.state.arr.map(item => (
          <TaskBoard taskType={item} />
        ))}
      </div>
    );
  }
}

Доска задач. js

import React from "react";

export default function TaskBoard(props) {
  return <div style={{ color: "tomato" }}> {props.taskType}</div>;
}
...