问题
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