How do I get submitted form value in React?

旧城冷巷雨未停 提交于 2020-01-14 06:47:26

问题


Here is my React Component

import React, { Component } from 'react';
import categories from './categories.json'
import './content.css'

export default class Content extends Component {
    constructor(props) {
        super(props)
        this.state = {
            searchText: '',
            categories
        }
    }

    render() {
        return(
            <div className="content">
            <form className="searchform" onSubmit={this.search}>
                <input type="text" name="keyword" id="searchbox" placeholder="Search String"></input>
                <select name="categories" id="searchcategories">
                <option defaultValue="" defaultChecked>Select a category</option>
                {this.state.categories.map(x => 
                    <option key={x.value} value={x.value}>{x.name}</option>
                )}</select>
                <input type="submit" value ="Search" id="searchsubmit" />
            </form>
            </div>
        )
    }

    search(e) {
        console.log(e.target)
        e.preventDefault();
    }
}

On clicking the submit button, my function search does get called. However, how do I get the submitted values?

e.target gives me the whole form DOM HTML e.target.value is undefined


回答1:


In React, you have two options for form components:

Controlled components (https://reactjs.org/docs/forms.html#controlled-components) have their value linked to component state by setting their value prop to a state variable. In this scenario, you can use your component's this.state to inspect their values.

Uncontrolled components (https://reactjs.org/docs/uncontrolled-components.html) can have references attached to their parent component when instantiated... typically like this ref={(input) => this.input = input}. When your function search is called, you can inspect the reference for the value, i.e. this.input.value.




回答2:


You need to use the state variables for this. For example sync this.state.searchText with the element whenever text changes. And then define a callback mechanism like -

onSubmit={()=>{
console.log('My searchBox's latest value is : ',this.state.searchText);
}}

Remember, in React we follow a unidirectional flow. So, we always take our data from props or states, and do not need to work on DOM traversals.



来源:https://stackoverflow.com/questions/47842514/how-do-i-get-submitted-form-value-in-react

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!