【发布时间】: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(
[<>]工具栏按钮)的 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