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(). 方法进行更新.
实例演练:


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中这种绑定方式已经封装好了,只需要一个标签即可。

如果觉得文章写得还行,请点个赞。如果想与我进一步交流,可以关注我的公众号或者加我的微信。

个人微信

公众号_前端微说.jpg
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容