onClick不会呈现其他React组件

时间:2019-05-20 09:18:03

标签: javascript reactjs react-native

我创建了一个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>
      );
  }
}

现在,单击我其他班级的按钮时,什么也没发生。

1 个答案:

答案 0 :(得分:2)

在我看来,主要问题是您的render方法正在尝试直接渲染承诺,就像异步onShare()方法返回的那样。相反,您应该使异步代码更新组件的状态,然后可以触发基于该状态值而不是基于onShare()

的直接输出的渲染。