学習めも。

Python、Anaconda学習中🔰 ブログ引っ越ししました😄よろしくお願いします!https://noeiganolife.com/

記録用🔰

プログラミング以外の記事はこちら

Reactでフォームをつくる

参考

f:id:Moriane:20201206201420p:plain f:id:Moriane:20201206201605p:plain

サンプル

import React from 'react';

class ContactForm extends React.Component {
  render() {
    return (
      <div className='contact-form'>
        <form>
          <p>メールアドレス(必須)</p>
          {/* inputタグを追加 */}
          <input />
          
          <p>お問い合わせ内容(必須)</p>
          {/* textareaタグを追加 */}
          <textarea />
          
          {/* 送信ボタンを追加 */}
          <input            
            type='submit'            
            value='送信'            
          />
          
        </form>
      </div>
    );
  }
}

export default ContactForm;

フォームの入力や削除が行われたときに処理を実行

→onChangeイベントを用いる。

・inputタグに対してonChangeイベントを指定。

・入力値の取得は、onChangeイベントの関数にeventという引数を追加し、event.target.valueとすると取得できる。

・eventとevent.target.valueはセットで覚えるとよい

・handleEmailChangeメソッドをつくりstateの変更を行う。

・メソッドにeventを渡していることに注目。こうすることでメソッド内で入力値を取得できる。

・メールアドレスの入力値が空かどうかを判定するために、handleEmailChangeメソッドに以下の処理を追加

・複数のstateを更新する場合、コンマ(,)で区切り一度のsetStateでまとめて変更

import React from 'react';

class ContactForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isSubmitted: false,
      email: '',
      /* hasEmailErrorを追加 */
      hasEmailError: false
    };
  }

  handleEmailChange(event) {
    const inputValue = event.target.value;
    this.setState({email: inputValue});
  }

  handleSubmit() {
    this.setState({isSubmitted: true});
  }

  render() {
    /* 変数emailErrorTextを定義 */
    let emailErrorText;
    
    /* hasEmailErrorを条件にしたif文を作成 */
    if(this.state.hasEmailError){
      emailErrorText = (
        <p className='contact-message-error'>
          メールアドレスを入力してください
        </p>  
      );
    }

    let contactForm;
    if (this.state.isSubmitted) {
      contactForm = (
        <div className='contact-submit-message'>
          送信完了
        </div>
      );
    } else {
      contactForm = (
        <form onSubmit={() => {this.handleSubmit()}}>
          <p>メールアドレス(必須)</p>
          <input
            value={this.state.email}
            onChange={(event) => {this.handleEmailChange(event)}}
          />
          {/* emailErrorTextを表示*/}
          {emailErrorText}
          
          <p>お問い合わせ内容(必須)</p>
          <textarea />
          <input
            type='submit'
            value='送信'
          />
        </form>
      );
    }

    return (
      <div className='contact-form'>
        {contactForm}
      </div>
    );
  }
}

export default ContactForm;

※if文書くときにセミコロンの書き忘れ多し!要注意!!

入力チェックをいれる

import React from 'react';

class ContactForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isSubmitted: false,
      email: '',
      hasEmailError: false,
    };
  }

  handleEmailChange(event) {
    const inputValue = event.target.value;
    /* 定数isEmptyを定義し、入力チェックの結果を代入 */
    const isEmpty = inputValue === '';
    
    /* hasEmailErrorを更新 */
    this.setState({            
      email: inputValue,            
      hasEmailError: isEmpty,
    });
  }

  handleSubmit() {
    this.setState({isSubmitted: true});
  }

  render() {
    let emailErrorText;
    if (this.state.hasEmailError) {
      emailErrorText = (
        <p className='contact-message-error'>
          メールアドレスを入力してください
        </p>
      );
    }

    let contactForm;
    if (this.state.isSubmitted) {
      contactForm = (
        <div className='contact-submit-message'>
          送信完了
        </div>
      );
    } else {
      contactForm = (
        <form onSubmit={() => {this.handleSubmit()}}>
          <p>メールアドレス(必須)</p>
          <input
            value={this.state.email}
            onChange={(event) => {this.handleEmailChange(event)}}
          />
          {emailErrorText}
          <p>お問い合わせ内容(必須)</p>
          <textarea />
          <input
            type='submit'
            value='送信'
          />
        </form>
      );
    }

    return (
      <div className='contact-form'>
        {contactForm}
      </div>
    );
  }
}

export default ContactForm;

hasContentErrorと条件分岐を用いてエラーメッセージを表示(内容のstate管理)

・stateを変更するメソッド(handleContentChange)は引数にeventを指定  また、メソッド内で3つの処理を行う

 ①定数inputValueを定義し、引数eventを用いて入力値を代入(入力値はevent.target.valueで取得)

 ②定数isEmptyを定義し、inputValueが空文字列かどうかを代入( 空文字列かどうかのチェックはinputValue === ''とする)

 ③stateのcontentとhasContentErrorを更新(contentはinputValue、hasContentErrorはisEmptyの値に更新)

・お問い合わせ欄への入力時にメソッドを呼び出し  textareaタグにonChangeイベントを追加し、handleContentChangeメソッドが実行されるようにする

・エラーメッセージを用意

 ①renderメソッド内で、変数contentErrorTextを定義

 ②stateのhasContentErrorがtrueのとき、変数contentErrorTextに下記のJSXを代入

 ③最後に<textarea … />の下で、contentErrorTextを表示  

import React from 'react';

class ContactForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isSubmitted: false,
      email: '',
      hasEmailError: false,
      <span style="color: #9FD6D2">/* contentとhasContentErrorというstateを追加 */</span>
      content: '',
      hasContentError: false
    };
  }

  handleEmailChange(event) {
    const inputValue = event.target.value;
    const isEmpty = inputValue === '';
    this.setState({
      email: inputValue,
      hasEmailError: isEmpty
    });
  }

  <span style="color: #9FD6D2">/* handleContentChangeという名前のメソッドを定義 */</span>
  handleContentChange(event) {
    const inputValue = event.target.value;            
    const isEmpty = inputValue === '';            
    this.setState({            
      content: inputValue,            
      hasContentError: isEmpty           
    })
  }
  

  handleSubmit() {
    this.setState({isSubmitted: true});
  }

  render() {
    let emailErrorText;
    if (this.state.hasEmailError) {
      emailErrorText = (
        <p className='contact-message-error'>
          メールアドレスを入力してください
        </p>
      );
    }
    
    <span style="color: #95c7a4">/* 変数contentErrorTextを定義 */</span>
    let contentErrorText;
    
    
    <span style="color: #9FD6D2">/* hasContentErrorを条件にしたif文を作成 */</span>
    if (this.state.hasContentError) {            
      contentErrorText = (            
        <p className='contact-message-error'>            
          お問い合わせ内容を入力してください            
        </p>            
      )            
    }
    
    let contactForm;
    if (this.state.isSubmitted) {
      contactForm = (
        <div className='contact-submit-message'>
          送信完了
        </div>
      );
    } else {
      contactForm = (
        <form onSubmit={() => {this.handleSubmit()}} >
          <p>メールアドレス(必須)</p>
          <input
            value={this.state.email}
            onChange={(event) => {this.handleEmailChange(event)}}
          />
          {emailErrorText}
          <p>お問い合わせ内容(必須)</p>
          <span style="color: #62c7c9">{/* stateのvalueの値と、onChangeイベントを追加 */}</span>
          <textarea            
            value={this.state.content}            
            onChange={(event) => {this.handleContentChange(event)}}            
          />            
          <span style="color: #95c7a4">{/* contentErrorTextを表示*/}</span>            
          {contentErrorText}
          
          <input
            type='submit'
            value='送信'
          />
        </form>
      );
    }
    
    return (
      <div className='contact-form'>
        {contactForm}
      </div>
    );
  }
}

export default ContactForm;