gpt4 book ai didi

javascript - onClick 不渲染不同的 react 组件

转载 作者:行者123 更新时间:2023-12-01 00:59:32 27 4
gpt4 key购买 nike

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

现在,点击我的其他类(class)的按钮没有任何反应。

最佳答案

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

的直接输出

关于javascript - onClick 不渲染不同的 react 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56217793/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com