我已经创建了一个SocialShare组件,当单击任何其他组件上的Share按钮时,我希望呈现该组件。
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>
);
}
}现在,在我的另一个类中单击按钮时没有任何反应。
发布于 2019-05-20 17:32:32
在我看来,主要问题是您的render方法试图直接呈现promise,而异步onShare()方法将返回该promise。相反,您应该让异步代码更新组件的状态,这样就可以触发基于该状态值的呈现,而不是基于onShare()的直接输出
https://stackoverflow.com/questions/56217793
复制相似问题