簡體   English   中英

在React-Native中按下按鈕不返回組件

[英]Not returning a component on button press in React-Native

我是本機框架的初學者。 我正在構建一個示例移動應用程序。 而且我堅持最基本的步驟。 我試圖在點擊事件上調用“ getBusinessNews()”函數,該函數將返回一個組件。 但是由於某種原因,它沒有返回。 我已經仔細檢查了組件的路徑及其正確性。 甚至顯示在函數內部定義的console.log。 我附上了代碼,感謝所有幫助。 先感謝您。

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;

event handler/listener返回組件以進行渲染將不起作用。 取而代之的是進行state update以確定組件BusinessNews是否將呈現。

它應該這樣做。

建設者

constructor() {
  this.state = {
    showBusiness: false//initially set to false
  }
}

getBusinessNews

getBusinessNews() {
  this.setState({showBusiness: true})//set to true to show BusinessNews
}

渲染

render() {

  render() {
    return (
      <View>
        <TouchableOpacity
          onPress={this
          .getBusinessNews
          .bind(this)}>
          {this.state.showBusiness ===true && <BusinessNews/>}//check boolean true 
          <Text>Business News</Text>
        </TouchableOpacity>
      </View>
    );
  }

}

您可以點擊返回組件。 因為您必須僅返回render()中的 component。 您需要更改邏輯以渲染組件。

您可以在render()中的某個位置調用<BusinessNews />以添加組件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM