本机新手。我需要从外部函数渲染组件。我知道我可以使用状态道具来实现它,但是我需要以这种方式做到这一点,因为我需要其他类等可重用它。
正如您在下面看到的,我试图将其返回,但是它不起作用。当我单击按钮时,什么也没有发生。 然后,我尝试完全调用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'放在render函数中,则它可以正常工作,因此我认为组件类中没有问题。 如您所料,这是我想在单击“按钮”时显示的模式。 你们有什么主意吗?
编辑: 解决了!基于@milanika解决方案,我在组件类中添加了以下代码:
componentWillUpdate() {
if (this.state.isVisibleState !== this.props.isVisible) {
this.setState({isVisibleState: this.props.isVisible});
}
}
其中isVisibleState是组件的状态道具,而isVisible是我从myClass传递的内容。
答案 0 :(得分:0)
仅返回该组件无济于事,您将不得不在render函数中的某处使用返回的代码段,如下面的示例
import React, {Component} from 'react';
import {View,Text, TouchableOpacity} from 'react-native';
import PopupComponent from './PopupComponent/PopupComponent'
export default class myClass extends Component{
constructor() {
super()
this.state = { showPopup: false }
}
render(){
return(
<View>
<TouchableOpacity onPress={() => { this.setState({ showPopup: true }) }}>
<Text>PressButton</Text>
</TouchableOpacity>
{this.state.showPopup === true ? (<PopupComponent isVisible={true} />) : (null)}
</View>
)
}
}
您可以测试代码here
答案 1 :(得分:0)
好吧,两件事:
如果要在单击后渲染它,只需为其设置一个状态/属性,然后通过showPopup函数将其切换,例如
import React, {Component} from 'react';
import {View, Text, TouchableOpacity} from 'react-native';
import PopupComponent from './PopupComponent/PopupComponent'
export default class myClass extends Component {
constructor() {
super()
this.state = { showPopup: false }
}
showPopup = () => {
this.setState({showPopup: true})
};
render(){
const { showPopup } = this.state;
return(
<View>
<TouchableOpacity onPress={this.showPopup}>
{showPopup && <PopupComponent isVisible={true}/> }
<Text>PressButton</Text>
</TouchableOpacity>
</View>
)
}
}
如果您的PopupComponent中具有isVisible属性,则可以将showPopup状态作为prop传递给该属性,并在这种情况下直接将其放置在render方法上,而无需在myClass Component上添加任何逻辑,但在这种情况下,如果this.props.isVisible为true,则Popupcomponent返回null虚假的价值。