正如标题所说,我总是无法从输入字段获得价值。它总是空的(可能初始状态在提交时不会改变)。有人能指出我正确的方向
import React, {Component} from 'react';
import SearchBar from '../components/SearchBar';
class FormContainer extends Component {
constructor(props) {
super(props);
this.state = {
cityName: '',
};
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.handleCityName = this.handleCityName.bind(this);
}
handleFormSubmit(e) {
e.preventDefault();
const SendForm = {
cityName: this.state.cityName
};
console.log(SendForm);
}
handleCityName(e) {
this.setState({ cityName: e.target.value });
}
render() {
return (
<form onSubmit={this.handleFormSubmit}>
<label>{this.props.label}</label>
<SearchBar name="CityName" type="text" value={this.state.cityName} placeholder="search" onSubmit={this.handleCityName}/>
<button type="submit"
className=""
value='Submit'
placeholder="Search" />
</form>
);
}
}
export {FormContainer};
这是搜索栏组件
import React, {Component} from 'react';
const SearchBar = (props) => (
<div>
<label>{props.label}</label>
<input name={props.name} type={props.inputType} value={props.cityName} placeholder={props.placeholder} />
</div>
);
export default SearchBar;
修改
class FormContainer extends Component {
constructor(props) {
super(props);
this.state = {
cityName: '',
};
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.handleCityName = this.handleCityName.bind(this);
}
handleFormSubmit(e) {
e.preventDefault();
const SendForm = {
cityName: this.state.cityName
};
console.log(SendForm);
}
handleCityName(e) {
this.setState({ cityName: e.target.value });
}
render() {
return (
<form onSubmit={this.handleFormSubmit}>
<label>{this.props.label}</label>
<input name="CityName" type="text" value={this.state.cityName} placeholder="search"/>
<button type="submit"
className=""
value='Submit'
placeholder="Search" />
</form>
);
}
}
答案 0 :(得分:2)
原因是您没有更新cityName
中的parent component
。
解决方案:从onChange
传递parent component
方法,如下所示:
<SearchBar name="CityName" type="text" value={this.state.cityName} placeholder="search" onChange={this.handleCityName}/>
handleCityName(value) {
this.setState({ cityName: value });
}
使用此method
并将用户输入的value
传递回parent
,如下所示:
<input name={props.name} type={props.inputType} value={props.value} placeholder={props.placeholder} onChange={(e)=>props.onChange(e.target.value)}/>
查看jsfiddle
上的工作示例:https://jsfiddle.net/wzez3yc1/
如果您需要任何帮助,请告诉我。