简体   繁体   中英

How to capture form input with react-redux

I've read a few stackoverflow answers to this question and the answers I've seen either require the use of another module (react form) or seem hacky and over complicated.

The goal of the code below is to simply capture the input of the form as e.target.value and log the information to the console. The problem is e.target.value returns undefined and I do not know why, nor do I know the recommended way to capture form input using react-redux. I want to know the recommended way to do this without the use of a third party module.

import React, { Component } from 'react';
import { connect } from 'react-redux';



class Form extends Component {
    constructor(props){
        super(props)

        this.state = {
            data: ""
        }

        this.handleChange = this.handleChange.bind(this)
    }

    handleChange(e){
        this.setState({
            data: e.target.value
        })
    }

    render() {
        return (
        <div>

            <form onSubmit={this.props.togglePlayAction}>
            <input type="text" value = {this.state.data} onChange={this.handleChange}/>
            <input type="submit"/>
            </form>
        </div>
        );
    }
}




const mapDispatchToProps = (dispatch) => {
    return {
        togglePlayAction:(e)=>{
            e.preventDefault()
            console.log(e.target);        // form is output
            console.log(e.target.value); // undefined

        }
    }
}

export default connect(mapDispatchToProps)(Form);
handleChange(e){
        this.setState({
            data: e.target.value
        })
    }

this.set.state is async. this will not work. because async function does not run right away. so u should handle it like this:

 handleChange = e => {
    const note = e.target.value; //name what ever u want
    this.setState(() => ({ date:note }));
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM