簡體   English   中英

onClick不會呈現其他React組件

[英]onClick not rendering a different react component

我已經創建了一個SocialShare組件,當我在任何其他組件上單擊“共享”按鈕時,都希望呈現該組件。

import React, {Component} from 'react';
import {View, Share, Button} from 'react-native';

export class SocialShare extends Component {

  onShare = async () => {
    try {
      const result = await Share.share({
        message:
          'React Native | A framework for building native apps using React',
      });

      if (result.action === Share.sharedAction) {
        if (result.activityType) {
          // shared with activity type of result.activityType
        } else {
          // shared
        }
      } else if (result.action === Share.dismissedAction) {
        // dismissed
      }
    } catch (error) {
      alert(error.message);
    }
  };

  render() {
    return (

      this.onShare()

      );
  }
}

這就是我從另一個組件調用此組件的方式:

<View>
    <Button onClick={() => this.onShareButtonClick()}>Button</Button>
         {this.state.showShareComponent ?
             <SocialShare /> :
             null
         }
</View>

onShareButtonClick函數:

onShareButtonClick(){        
        this.setState({
            showShareComponent: !this.state.showShareComponent,
        })
    }

單擊按鈕時,這是我得到的錯誤:

Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65, _55, _72}). If you meant to render a collection of children, use an array instead.
    in SocialShare 

我的代碼有什么問題?

編輯:根據建議,將我的SocialShare類修改為:

import React, {Component} from 'react';
import {View, Share, Button} from 'react-native';

export class SocialShare extends Component {
  constructor(props) {
    super(props);
    this.state = {
        asyncCompleted: false,
    };
  }
  onShare = async () => {
    try {
      const result = await Share.share({
        message:
          'React Native | A framework for building native apps using React',
      }).then(
        this.setState({asyncCompleted: true})
      );



      if (result.action === Share.sharedAction) {

        if (result.activityType) {
          // shared with activity type of result.activityType
        } else {
          // shared
        }
      } else if (result.action === Share.dismissedAction) {
        // dismissed
      }
    } catch (error) {
      alert(error.message);
    }
  };


  render() {
    return (

      <View>
      {this.state.asyncCompleted ? this.onShare() : null}
      </View>
      );
  }
}

現在,單擊我其他班級的按鈕時,什么也沒有發生。

在我看來,主要問題是您的render方法正在嘗試直接渲染承諾,就像異步onShare()方法返回的onShare() 相反,您應該使異步代碼更新組件的狀態,然后可以觸發基於該狀態值而不是onShare()的直接輸出的onShare()

暫無
暫無

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

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