1. 程式人生 > >React 資料雙向繫結 以及鍵盤onChange 事件

React 資料雙向繫結 以及鍵盤onChange 事件

React 事件以及form 表單中的應用;

初步探索:

        記錄程式碼手法:資料的雙向繫結:

import React from 'react'
import './../assets/css/common.css'
const o_price = 20;
const o_num = 1;
class Model extends React.Component {


    constructor(props) {
        super(props);
        this.state = {
            price: o_price,
            num: o_num,
            sum: o_price*o_num,
            dev: 1
        }


    }

    setValue(e) {

        let pession = {};
        let value = e.target.value;
        let name = e.target.name;
        pession[name] =  parseInt(value);
        if(name == "num"){
            pession['sum'] = this.state.price*value;
        }else{
            pession['sum'] = this.state.num*value;
        }
        pession['dev'] = (pession['sum']-this.state.sum)/this.state.sum;
        //setState 方法是yibu
        this.setState(pession)
        
    }

    getSum(e) {

    }
    render() {
        return (
            <div>
                <div className="form-control">
                    預設價格: <span className="label">{o_price}</span>
                    預設數量: <span className="label">{o_num}</span>
                </div>
                <div className="form-control">
                    <span className="label">單價:</span>
                    <input onChange={(e)=>this.setValue(e)} type="number" defaultValue={this.state.price} name="price"/>
                </div>

                 <div className="form-control">
                    <span className="label">數量:</span>
                    <input onChange={(e)=>this.setValue(e)} type="number" defaultValue={this.state.num} name="num" />
                </div>
            
                <div className="form-control">
                    <span className="label">總價:</span>
                    <input type="number" onChange={(e)=>this.getSum(e)} value={this.state.sum} name="sum"/>
                </div>
                <div>
                </div>

            </div>
        )
    }
}

export default Model;