2016-04-22 82 views
2

我写了一个点击处理程序来解析Google Play商店URL的下载按钮。立即在React Native中调用Click Handler

问题是,当页面加载时,URL被立即访问。

点击处理程序嵌套在onPress属性中,我不按任何东西,所以我很努力地理解为什么会发生这种情况。

任何帮助,将不胜感激!

OpenURL.js:

'use strict'; 
import React, { 
    Component, 
    PropTypes, 
    Linking, 
    StyleSheet, 
    Text, 
    TouchableNativeFeedback, 
    TouchableHighlight, 
    View 
} from 'react-native'; 

class OpenURLButton extends Component { 

    constructor(props) { 
    super(props); 
    } 

    handleClick(url) { 
    console.log(url); 
    console.log('handling click! this is : '); 
    console.dir(this); 
    Linking.canOpenURL(this.props.url).then(supported => { 
     if (supported) { 
     Linking.openURL(this.props.url); 
     } else { 
     console.log('Don\'t know how to open URI: ' + this.props.url); 
     } 
    }); 
    } 

    render() { 
    console.log('logging "this" inside render inside OpenURL.js:'); 
    console.dir(this); 
    return (
     <TouchableHighlight onPress={this.handleClick(this.props.appStoreUrl)}> 
     <Text>Download {this.props.appStoreUrl}</Text> 
     </TouchableHighlight> 
    ); 
    } 

} 


OpenURLButton.propTypes = { 
    url: React.PropTypes.string, 
} 

export default OpenURLButton; 

Inventory.js:

<ScrollView> 
     <View style={styles.ImageContainer}> 
     <Image style={styles.ImageBanner} source={{uri: selectedInventory.bannerImage}} /> 
     </View> 
     <View style={styles.ListGridItemCaption}> 
     <Image style={[styles.ImageThumb, styles.ImageGridThumb]} source={{uri: selectedInventory.thumbImage}} /> 
     <Text style={styles.Text} key="header">{name}</Text> 
     </View> 
     <View> 
     <Text>{selectedInventory.description}</Text> 
     <OpenURLButton url={selectedInventory.appStoreUrl}/> 
     </View> 
    </ScrollView> 

回答

3

变化:

<TouchableHighlight onPress={this.handleClick(this.props.appStoreUrl)}> 
    <Text>Download {this.props.appStoreUrl}</Text> 
</TouchableHighlight> 

要:

<TouchableHighlight onPress={() => {this.handleClick(this.props.appStoreUrl)}}> 
    <Text>Download {this.props.appStoreUrl}</Text> 
</TouchableHighlight> 

随着更改,您正在创建调用“您的”方法的匿名函数。这工作。

+0

要走的路!谢谢!! –

+0

对不起,这个,但我已经尝试(并失败)找到为什么需要使用匿名函数,以防止方法在页面加载触发文档。 有没有什么地方的onPress /任何事件处理程序的行为之间的差异,当在“本地”(住在同一个类)方法与“远程”(即:this.props.doStuff ) 方法。 我有上面描述的问题,当我使用本地方法,我宁愿明白为什么然后做一些“只是因为”。非常感谢。 –