【发布时间】:2019-11-22 22:18:44
【问题描述】:
react-native 新手在这里。我需要从外部函数渲染组件。我知道我可以使用 state prop 来实现,但我需要这样做,因为我需要它可重用其他类等。
如下所示,我尝试将其退回,但它不起作用。当我单击按钮时,没有任何反应。 然后,我尝试一路调用onPress函数,比如()=>this.showPopup、this.showPopup和this.showPopup()(最后一个完全错了)。
import React, {Component} from 'react';
import {View,Text, TouchableOpacity} from 'react-native';
import PopupComponent from './PopupComponent/PopupComponent'
export default class myClass extends Component{
showPopup = () =>{
return(<PopupComponent isVisible={true}/>)
};
render(){
return(
<View>
<TouchableOpacity onPress={()=>this.showPopup}>
<Text>PressButton</Text>
</TouchableOpacity>
</View>
)
}
}
如果我将组件“PopupComponent”放在渲染函数中,它可以正常工作,所以我认为组件类中没有问题。 正如您所猜想的那样,当我单击 PressButton 时,我希望它是一种可见的模式。 你们有什么想法吗?
编辑: 解决了!基于@milanika 解决方案,我在组件类中添加了以下代码:
componentWillUpdate() {
if (this.state.isVisibleState !== this.props.isVisible) {
this.setState({isVisibleState: this.props.isVisible});
}
}
其中 isVisibleState 是组件的 state prop,isVisible 是我从 myClass 传递的。
【问题讨论】:
-
编辑:显然有组件的导入
标签: typescript react-native components