![](/img/trans.png)
[英]Updating Parent component state from Child component TextInput in React Native
[英]React - Updating Parent State from Child Form Component
我正在尝试通过子组件<Form handler = {this.handler} />
更新状态。 但是当我按下Enter键时,当前状态值为null。 我认为问题出在我的handler(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;
您已经在App
定义了handleChange
并将其传递给Form
。 但是,而不是使用传递的prop函数,而是再次在Form
组件中创建一个新函数handleChange
。 您还已经在两个组件中声明了value
状态。 使用handleChange
prop函数来处理更改,而不是创建一个新的更改,
<FormControl
type="text"
value={this.state.value}
placeholder="Enter text"
onChange={this.props.handleChange}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.