S
S
Space Around2019-07-25 15:59:40
JavaScript
Space Around, 2019-07-25 15:59:40

How to pass data from child to parent component on button click in React?

There is a parent form component inside which there are 2 child components input and button.
Question: How to implement getting the value of the state, which belongs to the input component in sate, which belongs to the form on clicking the button?
Addition: Very briefly, we press the button and the value of the state input'a is assigned to the value of the state forma. Interested in just such a condition.
form

spoiler
import React from 'react'
import InputText from './InputText'
import Button from './Button'

class Forma extends React.Component {
    constructor (props) {
        super (props);
        this.state = {
            value: '',
        }
    }

    render () {
        return (
            <div>
                <InputText updateData = {this.updateData1} /><br/>
                <Button />
            </div>
        )
    }
}

export default Forma

input
spoiler
import React from 'react'

class InputText extends React.Component {
    constructor (props) {
        super (props);
        this.state = {
            value: ''
        }
        this.handleChange = this.handleChange.bind(this);
    }

    handleChange (event) {
        this.setState({value: event.target.value});
    }

    render () {
        return (
            <input type="text" onChange={this.handleChange} value={this.state.value}/>
        )
    }
}

export default InputText

button
spoiler
import React from 'react'

class Button extends React.Component {
    constructor (props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
    }

    handleClick(e) {
      e.preventDefault();
    }

    render () {
        return (
            <button onClick={this.handleClick}>Отправить</button>
        )
    }
}

export default Button

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Marat Ivanov, 2019-07-25
@viksnamax

In this case, put the event handlers in the form and not in the input, and lower the callbacks with props in the button and input.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question