React官网学习实践 - 表单

HTML表单元素与React中的其他DOM元素有所不同,因为表单元素生来就保留一些内部状态。例如,下面这个表单只接受一个唯一的name。

<form>
  <label>
    Name:
    <input type="text" name="name" />
  </label>
  <input type="submit" value="Submit" />
</form>

在HTML当中,像<input>,<textarea>, 和 <select>这类表单元素会维持自身状态,并根据用户输入进行更新。但在React中,可变的状态通常保存在组件的状态属性中,并且只能用 setState(). 方法进行更新.
实例演练:

2789632-26146b0c1e0fe0c5.gif

Code:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            value: ''
        };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }
    handleChange(event) {
        this.setState({value: event.target.value});
    }
    handleSubmit(event){
        alert('A name was submitted:' + this.state.value);
        event.preventDefault();
    }
    componentWillMount () {
        console.log('this is in componentWillMount method.');

    }
    componentDidMount () {
        console.log('this is in componentDidMount method.');
    }
    componentWillReceiveProps (nextProps) {
        console.log('this is in componentWillReceiveProps method.');
    }
    // shouldComponentUpdate (nextProps,nextState) {
    //     console.log('this is in shouldComponentUpdate method.');
    // }
    componentWillUpdate (nextProps,nextState) {
        console.log('this is in componentWillUpdate method.');
    }
    componentDidUpdate (prevProps,prevState) {
        console.log('this is in componentDidUpdate method.');
    }

    render() {
    return (
        <div>
        <form onSubmit={this.handleSubmit}>
        <label>
            Name:
            <input type="text" value={this.state.value} onChange={this.handleChange} />

        </label>
            <input type="submit" value="submit" />
        </form>
            <p>value is: {this.state.value}</p>
        </div>

    );
  }
    componentWillUnmount () {
        console.log('this is in componentWillUnmount method.');
    }
}

export default App;

此处写了两个事件函数,一个是change, 一个是submit.
由于 value 属性是在我们的表单元素上设置的,因此显示的值将始终为 React数据源上this.state.value 的值。由于每次按键都会触发 handleChange 来更新当前React的state,所展示的值也会随着不同用户的输入而更新。
这也挺像在vue中的v-model的使用,只是在vue中这种绑定方式已经封装好了,只需要一个标签即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值