Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6214

How to access and change child's state from Parent component

$
0
0

You are given uncontrollable child component.Parent component stores number of counters and renders that amount of child components. It has two buttons Add counter and Increment all counters.

  1. You are not allowed to edit child component.

  2. ImplementincrementCounters so that it increments counters of all childcomponents that are rendered.

    incrementCounters = () => {// TODO: implement};


export class ChildCounter extends React.Component{    state = {        counter: 0    };    increment = () => {        this.setState(({ counter }) => ({            counter: counter + 1        }));    };    render() {        return (<div>                Counter: {this.state.counter}<button onClick={this.increment}>+</button></div>        );    }}

import {ChildCounter} from "./Child";class App extends React.Component {    state = {counters:1}    addCounter = () => {     let counterRn = this.state.counters + 1;     this.setState({counters:counterRn})    };   incrementAll = () => {   }   render() {   return (<div>                { new Array(this.state.counters).fill(0).map((_, index) => {                    return <ChildCounter key={index} />;                })                }<br/><button style={{marginRight:10}} onClick={this.addCounter}>Add Counter</button><button onClick={this.incrementAll}>Increment all counters</button></div>   )   }}

Viewing all articles
Browse latest Browse all 6214

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>