首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >onClick未呈现不同的react组件

onClick未呈现不同的react组件
EN

Stack Overflow用户
提问于 2019-05-20 17:18:03
回答 1查看 98关注 0票数 0

我已经创建了一个SocialShare组件,当单击任何其他组件上的Share按钮时,我希望呈现该组件。

代码语言:javascript
复制
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()

      );
  }
}

这就是我从另一个组件调用这个组件的方式:

代码语言:javascript
复制
<View>
    <Button onClick={() => this.onShareButtonClick()}>Button</Button>
         {this.state.showShareComponent ?
             <SocialShare /> :
             null
         }
</View>

onShareButtonClick函数:

代码语言:javascript
复制
onShareButtonClick(){        
        this.setState({
            showShareComponent: !this.state.showShareComponent,
        })
    }

单击按钮时,这是我得到的错误:

代码语言:javascript
复制
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类修改为:

代码语言:javascript
复制
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>
      );
  }
}

现在,在我的另一个类中单击按钮时没有任何反应。

EN

回答 1

Stack Overflow用户

发布于 2019-05-20 17:32:32

在我看来,主要问题是您的render方法试图直接呈现promise,而异步onShare()方法将返回该promise。相反,您应该让异步代码更新组件的状态,这样就可以触发基于该状态值的呈现,而不是基于onShare()的直接输出

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56217793

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档