单击React Native中立即调用的Handler

时间:2016-04-22 20:57:26

标签: javascript reactjs react-native

我已经编写了一个点击处理程序来解析谷歌Play商店网址的下载按钮。

问题是,当页面加载时,会立即访问该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>

1 个答案:

答案 0 :(得分: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>

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

相关问题