首页 > 解决方案 > 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;

标签: javascriptreactjsreact-native

解决方案


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>
    );
  }

}

推荐阅读