javascript - Not returning a component on button press in React-Native
问题描述
I am a beginner in the react-native framework. I am building an sample mobile application. And I am stuck at the very basic step. I am trying to call 'getBusinessNews()' function on click event, which will return a component. But due to some reason, it's not returning. I have doubled checked the path of the component and its correct. Even the console.log defined inside the function is getting displayed. I am attaching the code, all kind of help is appreciated. Thank you in advance.
import React, {Component} from 'react';
import {Text,View,TouchableOpacity} from 'react-native';
import BusinessNews from '../News/BusinessNews';
class categories extends Component{
render(){
return(
<View>
<TouchableOpacity onPress={this.getBusinessNews.bind(this)}>
<Text>Business News</Text>
</TouchableOpacity>
</View>
);
}
getBusinessNews(){
console.log(1);
return(
<BusinessNews />
);
}
export default categories;
解决方案
Returning component from event handler/listener
to render will not work.
Instead do state update
to decide whether component BusinessNews
will render or not.
Its should do like this.
constructor
constructor() {
this.state = {
showBusiness: false//initially set to false
}
}
getBusinessNews
getBusinessNews() {
this.setState({showBusiness: true})//set to true to show BusinessNews
}
render
render() {
render() {
return (
<View>
<TouchableOpacity
onPress={this
.getBusinessNews
.bind(this)}>
{this.state.showBusiness ===true && <BusinessNews/>}//check boolean true
<Text>Business News</Text>
</TouchableOpacity>
</View>
);
}
}
推荐阅读
- angular - 如何为 PrimeNg 表格行应用动态样式?
- c - C. 链表问题。如何使用链表?
- heroku - npm 以 NODE_ENV 作为参数运行
- python - 我不知道为什么会出现“IndexError: list index out of range”
- amazon-web-services - 如何*安全*在 AWS EMR 引导脚本中从 github 安装 python 私有包
- c# - 创建具有泛型类型的接口集合
- amazon-web-services - 具有 2 个代理的两个 AZ 的出站 VPC 代理
- javascript - 节点 javascript 需要 js 文件?
- python - 如何在没有请求的情况下在 Scrapy 中屈服?
- ruby - Ruby 2.7 说 URI.escape 已经过时了,用什么代替它?