我是React原生的新手。我有一个noob问题,涉及将代码移离main函数render()并将代码放入不同的函数。
假设我有以下代码: -
render() {
return (
<View>
<Modal
animationType={"fade"}
transparent={true}
visible={this.state.signUpPopUpVisible}
onRequestClose={() => {alert("Modal has been closed.")}}>
{/* Other modal codes */}
</Modal>
<View style={styles.mainView}>
{/* Other mainView codes */}
</View>
</View>
);
}
如何移动整个代码
<Modal
animationType={"fade"}
transparent={true}
visible={this.state.signUpPopUpVisible}
onRequestClose={() => {alert("Modal has been closed.")}}>
{/* Other modal codes */}
</Modal>
进入另一个函数并在render()中调用它?
感谢。
答案 0 :(得分:2)
你可以尝试这样做,
showModal = () => {
return (<Modal
animationType={"fade"}
transparent={true}
visible={this.state.signUpPopUpVisible}
onRequestClose={() => { alert("Modal has been closed.") } }>
{/* Other modal codes */}
</Modal>);
}
render() {
return (
<View>
{this.showModal()}
<View style={styles.mainView}>
{/* Other mainView codes */}
</View>
</View>
);
}
答案 1 :(得分:2)
您只需要在另一个函数中返回对象,就像在渲染中一样。
示例:
yourFunction(){
return(
<View></View>
);
}
您的代码示例:
render() {
return (
<View>
{this._renderModal()}
<View style={styles.mainView}>
{this._renderMainViewCode()}/* Other mainView codes */
</View>
</View>
);
}
_renderModal(){
return(
<Modal
animationType={"fade"}
transparent={true}
visible={this.state.signUpPopUpVisible}
onRequestClose={() => {alert("Modal has been closed.")}}>
{this._renderModalCode()}/* Other modal codes */
</Modal>
);
}
_renderModalCode(){
return(
<Text>This is the modals code</Text>
);
}
_renderMainViewCode(){
return(
<Text>This is the main views code</Text>
);
}