I've created a SocialShare component which I want to render when Share button is clicked on any of my other components.
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()
);
}
}
This is how I am calling this component from another component:
<View>
<Button onClick={() => this.onShareButtonClick()}>Button</Button>
{this.state.showShareComponent ?
<SocialShare /> :
null
}
</View>
onShareButtonClick function:
onShareButtonClick(){
this.setState({
showShareComponent: !this.state.showShareComponent,
})
}
On click of button, this is the error I am getting:
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
What's wrong with my code?
Edit: As per suggestions, modified my SocialShare class to this:
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>
);
}
}
Now, nothing happens on click of button from my other class.
Seems to me like the main issue is that your render method is attempting to render a promise directly, as would be returned by the asynchronous onShare()
method. Instead, you should make the asynchronous code update the component's state, which can then trigger a render that will be based on this state value rather than the direct output of onShare()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.