fun*_*ker 5 javascript reactjs react-native
我创建了一个共享图标,单击该图标即可在 facebook、whatsapp、gmail 等社交帐户上共享 pdf 或图像文件。我想在类组件内传递可共享文件的 URL 链接,但出现错误。如果我对 URL 进行硬编码,那么它可以正常工作,但如何传递从反应导航收到的 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>
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码工作正常,但下面的代码给出错误,说shareOptions未定义。我怎样才能克服这个问题?我想在 .txt 文件中传递文件 URL shareOptions。我从反应导航道具中获取文件网址,即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>
)
}
Run Code Online (Sandbox Code Playgroud)
如何克服上述问题以及如何传递 props,即上述情况下的文件 URL,URL 位于brochureprops 中。
只需将 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>
)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6568 次 |
| 最近记录: |