0
0

More than 3 years have passed since last update.

React 学習①(Buttonクリック時にTextの値を渡す。)

Posted at

1 Buttonクリックしたときに、テキストの値を受け取りたい。

■やりたいこと

[テキストフィールド][ボタン]

ボタンクリックした時に、テキストフィールドの値を受け取りたい。
https://ja.reactjs.org/docs/forms.html

理解したイメージ
1.大枠のクラスの中にstateとして、変更される値(今回はテキストフィールドの値)を保持する入れ物を作成する。
2.handleChangeファンクションを作成して、テキストの値を変更したら、その値がstateの値を変更するようにする。この時、handleChange側に渡す引数のeは省略して書くと、あとでerrorのeと混同してしまうのは、まだ自分がjavaScriptに慣れていないからなのかもしれない。
3.ボタン側のイベントとしてhandleClickを用意する。handleClickで大域変数的なstateの値を利用することによって、ボタンで部品の値を受け取ることが可能。

Sample1.js
import React, { Component } from 'react';
import { Form, Button, Popover } from 'react-bootstrap'

class Sample1 extends Component {
    constructor(props) {
        super(props);
        this.state = {//使いたい値を入れる箱
            drink: null,
        };
        this.handleDrinkChoice = this.handleDrinkChoice.bind(this);
        this.handleDrinkClick = this.handleDrinkClick.bind(this);
    }

    handleDrinkChoice(event) {
        this.setState({ drink: event.target.value });
    }

    handleDrinkClick() {
        alert("your choice is :" + this.state.drink + ".");
    }

    render() {
        return (
            <div>
                <Form>
                    <Form.Group>
                        <Form.Label>coffe or tea</Form.Label>
                        <Form.Control type="text" placeholder="Input your choice."
                            value={this.state.drink} onChange={this.handleDrinkChoice} />
                    </Form.Group>
                </Form>
                <Button variant="primary" onClick={this.handleDrinkClick}>Submit</Button>
            </div>
        );
    }
}

export default Sample1;

*参考
https://www.it-swarm.dev/ja/javascript/reactjs%E3%81%A7%E3%83%95%E3%82%A9%E3%83%BC%E3%83%A0%E3%83%87%E3%83%BC%E3%82%BF%E3%82%92%E5%8F%96%E5%BE%97%E3%81%99%E3%82%8B/1046096180/

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0