score:0

import React, { Component } from 'react';

class List extends Component {
  newItem;
  constructor() {
    super();
    this.state = { items: [1, 2] };
    this.input = React.createRef();
  }
  changeNewItem = e => {
    this.newItem = e.target.value;
    console.log(this.newItem);
  };
  addItem = e => {
    if (e.keyCode !== 13 || !this.newItem) return;
    var new_list = this.state.items.concat(this.newItem);
    this.setState({ items: new_list }, () => {
      this.newItem = '';
      this.input.current.value = '';
    });
  };
  render() {
    return (
      <div>
        <ul>
          {this.state.items.map(item => (
            <li key={item}>{item}</li>
          ))}
        </ul>
        <input
          type="text"
          placeholder="add item"
          ref={this.input}
          onChange={this.changeNewItem}
          onKeyUp={this.addItem}
        />
      </div>
    );
  }
}

export default List;

score:1

import React, { Component } from 'react';

class List extends Component {
  constructor() {
    super();
    this.state = { items: [1, 2], newItem: '' };
  }
  changeNewItem = e => {
    this.setState({newItem: e.target.value})
  };
  addItem = e => {
    if (e.keyCode !== 13) return;
    var tmp_list = this.state.items;
    tmp_list.push(this.state.newItem);
    this.setState({ items: tmp_list }, () => {
      this.state.newItem = '';
    });
  };
  render() {
    return (
      <div>
        <ul>
          {this.state.items.map(item => (
            <li key={item}>{item}</li>
          ))}
        </ul>
        <input
          type="text"
          placeholder="add item"
          value={this.state.newItem}
          onChange={this.changeNewItem}
          onKeyUp={this.addItem}
        />
      </div>
    );
  }
}

export default List;

Related Query

More Query from same tag