react 獲取input標籤的輸入值

參考:https://segmentfault.com/a/1190000012404114react

 

兩種方法,受控組件和非受控組件。segmentfault

推薦使用受控組件,即經過this.state獲取,由於其符合react規範;this

受控組件示例,將文本框中字母轉爲大寫spa

<input
    type="text"
    value={this.state.value}
    onChange={(e) => {
        this.setState({
            value: e.target.value.toUpperCase(),
        });
    }}
/>

 

也能夠使用非受控組件,即給標籤指定ref屬性:code

import React, { Component } from 'react';

class UnControlled extends Component {
    handleSubmit = (e) => {
        console.log(e);
        e.preventDefault();
        console.log(this.name.value);
    }
    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <input type="text" ref={i => this.name = i} defaultValue="BeiJing" />
                <button type="submit">Submit</button>
            </form>
        );
    }
}

export default UnControlled;
相關文章
相關標籤/搜索