我创建了一个共享图标,单击它可以在社交帐户(如 facebook、whatsapp、gmail 等)上共享 pdf 或图像文件。我想在类组件内传递可共享文件的 URL 链接,但出现错误。如果我对 URL 进行硬编码,那么它可以正常工作,但我如何传递从 React 导航接收到的 URL?
工作代码:
import React, { Component } from 'react';
import { Share, View, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
const shareOptions = {
title: 'Download Brochure',
url: 'https://cpbook.propstory.com/upload/project/brochure/5bc58ae6ca1cc858191327.pdf'
}
export default class Screen extends Component {
onSharePress = () => Share.share(shareOptions);
render() {
return (
<View>
<Text style={styles.infoTitle}>Share: </Text>
<TouchableOpacity onPress={this.onSharePress}>
<Icon style={{paddingLeft: 10, paddingTop: 10}}name="md-share" size={30} color="black"/>
</TouchableOpacity>
</View>
}
}
上面的代码工作正常但下面的代码给出了错误提示 shareOptions
is undefined。我怎样才能克服这个问题?我想在 shareOptions
中传递文件 URL。我从 react 导航 Prop 中获取文件 url,即 brochure
。
代码:
import React, { Component } from 'react';
import { Share, View, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
export default class Screen extends Component {
onSharePress = () => Share.share(shareOptions); <---Getting error here shareOptions undefined
render() {
const project = this.props.navigation.getParam('project', null);
let { brochure } = project;
const shareOptions = {
title: 'Download Brochure',
url: brochure
}
return (
<View>
<Text style={styles.infoTitle}>Share: </Text>
<TouchableOpacity onPress={this.onSharePress}>
<Icon style={{paddingLeft: 10, paddingTop: 10}}name="md-share" size={30} color="black"/>
</TouchableOpacity>
</View>
)
}
如何克服上述问题以及如何传递 Prop ,即上述情况中的文件 URL URL 在 brochure
Prop 中。
最佳答案
只需将 shareOptions 对象作为参数传递给 onSharePress 函数,并在 onSharePress 事件处理函数中获取 shareOptions
import React, { Component } from 'react';
import { Share, View, TouchableOpacity } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
export default class Screen extends Component {
onSharePress = (shareOptions) => {
Share.share(shareOptions);
}
render() {
const { navigation } = this.props;
const project = navigation.getParam('project', null);
const { brochure } = project;
const shareOptions = {
title: 'Download Brochure',
url: brochure
}
return (
<View>
<Text style={styles.infoTitle}>Share: </Text>
<TouchableOpacity onPress={() => this.onSharePress(shareOptions)}>
<Icon style={{paddingLeft: 10, paddingTop: 10}}name="md-share" size={30} color="black"/>
</TouchableOpacity>
</View>
)
}
}
关于javascript - 如何在类组件中使用 React 导航 Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52878739/