Как правильно распространять изменения на дочерние компоненты? - PullRequest
1 голос
/ 10 июля 2020

Используя react-native, я не понимаю, как мне вносить изменения во вложенные структуры.

Я создал простой образец. Родитель владеет кнопкой. При нажатии количество кликов в родительском элементе будет увеличено. Как мне добиться увеличения количества кликов для ребенка? (в моем реальном сценарии я хочу, чтобы определенные c дочерние элементы были повторно отрисованы. Я понимаю, что поэтому мне нужно изменить какое-то состояние)

Родитель

var React = require('react');
import { StyleSheet, Text, View, Button } from 'react-native';
import Child from './Child';

class Parent extends React.Component {
  constructor(props) {
      super(props);
      this.state = {
        clickcount: this.props.clickcount,
      }

      child = (<Child clickcount={this.state.clickcount}/>);
  }

  handlePress() {
      console.log('Parent handlePress');
      this.increment();
  }

  increment() {
      this.setState({clickcount: this.state.clickcount+1});
  }



  render() {
    return (
      <View>
        <Text>Parent {this.state.clickcount}</Text>
      
        <Button
                    title="OK"
                    onPress={() => this.handlePress()}
                />
     </View>
    );
  }
}

export default Parent;

Дочерний

var React = require('react');
import { StyleSheet, Text, View, Button } from 'react-native';

class Child extends React.Component {
  constructor(props) {
      super(props);
      this.state = {
        clickcount: this.props.clickcount,
      }
  }

  handlePress() {
      console.log('Child handlePress');
      this.increment();
  }

  increment() {
      this.setState({clickcount: this.state.clickcount+1});
  }

  render() {
    return (
      <View>
        <Text>Child {this.state.clickcount}</Text>

     </View>
    );
  }
}

export default Child;

В настоящее время после 3х щелчков вывод выглядит следующим образом:

Родитель 3 Дочерний 0

1 Ответ

2 голосов
/ 10 июля 2020

Вы можете передать дочернему элементу функцию приращения, чтобы счетчик кликов принадлежал родителю

class Child extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this.props.increment}/>
        {this.props.clickCount}
      </div>
    )
  }
}


class Parent extends React.Component {
  state = {
    clickCount: 0
  }
  
  increment = () => {
    this.setState({ clickCount: this.state.clickCount + 1 })
  }
  
  render () {
    return (
      <Child increment={() => this.increment()} clickCount={this.state.clickCount}/>
    )
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...