JavaScript
JSX
React

Reactで垂れ流し一人チャットルーム

create-react-appで作成したプロジェクトのApp.jsを編集。
通信なし。リストを操作するだけ。

import React, { Component } from 'react';

class Response extends Component {

  render() {
    return (
      <div>
        <span>{this.props.name}</span>:
        <span>{this.props.content}</span> 
      </div>
    );
  }
}

class ResponseList extends Component {

  render() {
    return (
      <div>
        <ul>
            {this.props.responseList.map(r => <li>
              <Response name={r.name} content={r.content} />
            </li>)}
        </ul>
      </div>
    );
  }
}

class CommentForm extends Component {

  constructor(props) {
    super(props);
    this.state = {
      name: '',
      content: '',
    };

    this.handleNameChange = this.handleNameChange.bind(this);
    this.handleContentChange = this.handleContentChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleNameChange(ev) {
    this.setState({
      name: ev.target.value.toUpperCase(),
    })
  }

  handleContentChange(ev) {
    this.setState({
      content: ev.target.value,
    })
  }

  handleSubmit(ev) {
    ev.preventDefault();
    this.props.onSubmit(ev, this.state);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input type="text" value={this.state.name} onChange={this.handleNameChange} placeholder="Name" />
        <textarea value={this.state.content} onChange={this.handleContentChange} placeholder="Content">
        </textarea>
        <input type="submit" value="送信" />
      </form>
    );
  }
}

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      responseList: [],
    };

    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(ev, state) {
    this.state.responseList.push({
      name: state.name,
      content: state.content,
    });
    this.setState({
      responseList: this.state.responseList,  
    });
  }

  render() {
    return (
      <div className="App">
        <CommentForm onSubmit={this.handleSubmit} />
        <ResponseList responseList={this.state.responseList} />
      </div>
    );
  }
}

export default App;