React获取Input输入框的值

3,879 阅读1分钟

React获取input输入框的值

React获取输入框中的值两种方式:

  • 受控组件
  • 非受控组件

受控组件

import React, { Component } from 'react';

export default class App extends Component {

    search() {
        const inpVal = this.input.value;
    }

    render() {
        return (
            <div>
                <input
                    type="text"
                    ref={input => this.input = input}
                    defaultValue="Hello" />
                <button onClick={this.search.bind(this)}></button>
            </div>
        )
    }
}

非受控组件


import React, { Component } from 'react';

export default class App extends Component {

    constructor(props) {
        super(props);
        this.state = { inpValue: '' }
    }

    handelChange(e) {
        this.setState({ inpValu: e.target.value })
    }

    render() {
        return (
            <div>
                <input type="text"
                    onChange={this.handelChange.bind(this)}
                    defaultValue={this.state.inpValue} />
            </div>
        )
    }
}