简体   繁体   中英

React - Updating Parent State from Child Form Component

I am trying to update my state from my child component form <Form handler = {this.handler} /> . But when I hit enter, the current state value is null. I think the problem is in my handler(e) function but I don't know what it is.

 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; 

You have defined handleChange in App and passing it to Form . But instead of using the passed prop function, you are again creating a new function handleChange in Form component. You also have declared value state in both components. Use the handleChange prop function to handle the change instead of creating a new one,

<FormControl
    type="text"
    value={this.state.value}
    placeholder="Enter text"
    onChange={this.props.handleChange}
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM