我正在尝试从我的子组件表单<Form handler = {this.handler} />
更新我的状态。但是当我按Enter键时,当前状态值为null。我认为问题出在我的处理程序(e)函数中,但我不知道它是什么。
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Form from './Form.js';
import { Button } from 'react-bootstrap';
class App extends Component {
constructor(props) {
super(props);
this.handler = this.handler.bind(this)
this.state = {
value: 11
}
}
handler(e) {
e.preventDefault();
this.setState({
value: e.target.value
})
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<Button bsStyle='success'>Hello</Button>
<Form handler = {this.handler} />
<h1>{this.state.value}</h1>
</div>
);
}
}
export default App;
import React from 'react';
import {FormControl} from 'react-bootstrap';
import {FormGroup} from 'react-bootstrap';
import {ControlLabel} from 'react-bootstrap';
import {HelpBlock} from 'react-bootstrap';
import {InputGroup} from 'react-bootstrap';
class Form extends React.Component {
constructor(props, context) {
super(props, context);
this.handleChange = this.handleChange.bind(this);
this.state = {
value: ''
};
}
getValidationState() {
const length = this.state.value.length;
if (length > 10) return 'success';
else if (length > 5) return 'warning';
else if (length > 0) return 'error';
return null;
}
handleChange(e) {
this.setState({ value: e.target.value });
}
render() {
return (
<form onSubmit = {this.props.handler}>
<FormGroup
bsSize="small"
controlId="formBasicText"
validationState={this.getValidationState()}
>
<InputGroup>
<FormControl
type="text"
value={this.state.value}
placeholder="Enter text"
onChange={this.handleChange}
/>
<InputGroup.Addon>lbs</InputGroup.Addon>
</InputGroup>
<FormControl.Feedback />
</FormGroup>
</form>
);
}
}
export default Form;
答案 0 :(得分:1)
您已在handleChange
中定义App
并将其传递给Form
。但是,您不再使用传递的prop函数,而是再次在handleChange
组件中创建新函数Form
。您还在两个组件中声明了value
状态。使用handleChange
道具功能来处理更改,而不是创建新的
<FormControl
type="text"
value={this.state.value}
placeholder="Enter text"
onChange={this.props.handleChange}
/>