【问题标题】:How to get state of children from parent in class component如何从类组件中的父级获取子级的状态
【发布时间】:2021-12-11 14:59:58
【问题描述】:

我正在尝试在父组件中显示子组件的状态,但不知何故,文本“abcde”仍然没有显示,这是示例代码

import React from 'react';
import {SafeAreaView, StyleSheet, Text} from 'react-native';
import {TouchableOpacity} from 'react-native-ui-lib';

class ChidComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: '',
    };
  }
  render() {
    return (
      <SafeAreaView>
        <TouchableOpacity
          onPress={() => {
            this.setState({text: 'abcde'});
            this.props.getText(this.state.text);
          }}>
          <Text>Get Text</Text>
        </TouchableOpacity>
      </SafeAreaView>
    );
  }
}

const style = StyleSheet.create({
  text: {
    fontWeight: 'bold',
    fontSize: 40,
  },
});
class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: '',
    };
  }
  getTextFromChild(value) {
    this.setState({text: value});
  }
  render() {
    return (
      <SafeAreaView>
        <Text>{this.state.text}</Text>
        <ChidComponent
          getText={this.getTextFromChild.bind(this)}
          press={() => this.setState({show: !this.state.show})}
          textStyle={style.text}
        />
      </SafeAreaView>
    );
  }
}
export default ParentComponent;

但不知何故,屏幕仍然是空的,“abcde”仍然直到我点击两次,来自功能组件所以我不知道发生了什么,请帮助,非常感谢 p>

【问题讨论】:

  • 嗨!请使用 minimal reproducible example 来更新您的问题,以展示问题,最好是使用 Stack Snippets([&lt;&gt;] 工具栏按钮)的 runnable 问题。 Stack Snippets 支持 React,包括 JSX; here's how to do one。 (是的,问题是关于 React Native 的,但是绝大多数 React Native 的问题都是真正的 React 问题,你可以在 React 中模拟出来。)
  • 它可以运行 @T.J.Crowder,只是因为它是 react-native 所以我不能在这里运行它

标签: javascript reactjs react-native


【解决方案1】:

ParentComponent 中的 getTextFromChild 方法正在从状态中删除 show 属性,请将其更新为:

 getTextFromChild(value) {
    this.setState({text: value, show: true });
  }

编辑:setState 是异步的,您可以传递一个回调函数作为参数来访问更新的状态。

   <TouchableOpacity
          onPress={() => {
            this.setState({text: 'abcde'}, () => {
              this.props.getText(this.state.text);
           }); 
   }}>

应该可以。

【讨论】:

  • 谢谢你的回答,它可以运行,但我要按两次,我还是不明白
  • 我更新问题
  • 我还是不明白,我知道,async 函数是指function will not run in orderrun the same time,那么为什么当我按下 setState 时不会运行?但是非常感谢,该功能现在运行
  • 很高兴它有帮助!考虑支持并接受这个答案。关于 setState 是异步的,你可以在这里阅读:stackoverflow.com/a/36087156/3565182
猜你喜欢
  • 2021-12-04
  • 1970-01-01
  • 2019-02-03
  • 2015-04-23
  • 1970-01-01
  • 2020-01-14
  • 2021-08-15
  • 2021-11-05
  • 1970-01-01
相关资源
最近更新 更多