M
M
mashincode2020-11-02 17:08:29
React
mashincode, 2020-11-02 17:08:29

Catching child component change?

I have a parent component

class Parent extends React.Component {

    constructor(props) {
        super(props)
        this.testInputValue = ''
    }

    log_test_input_value = () => {
        console.log(this.testInputValue);
    }

    render() {
        return (
             <div>
              <button onClick={log_test_input_value}>Test log</button>
              <Child/>
            </div>
        )
    }
}


and child component

class Child extends React.Component {

    constructor() {
        super();
        this.testInputValue = "" ; //пусть инпут изначально пустой
    }

    handleChange(event) {
        this.testInput = event.target.value
    }

    render() {
          <input onChange={this.handleChange(e)} placeholder="test" /> 
        }
    }
}


They are in different files and the child is imported to the parent.
I want to change testInputValue in the child component, update it in the parent
How is this done correctly?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
8
8XL, 2020-11-02
@8XL

Store state in the parent component and pass methods in props to the child component.

class Parent extends React.Component {

    constructor(props) {
        super(props)
        this.testInputValue = ''
    }

    handleChange(event) {
        this.testInputValue = event.target.value
    }

    log_test_input_value = () => {
        console.log(this.testInputValue);
    }

    render() {
        return (
             <div>
              <button onClick={log_test_input_value}>Test log</button>
              <Child onChange={ this.handleChange }/>
            </div>
        )
    }
}

V
Vladimir, 2020-11-03
@Casufi

You didn't read the react documentation along the way.
https://reactjs.org/tutorial/tutorial.html#making-...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question