关于react native:onPress函数在页面加载时触发

onPress function firing on page load

背景

在我的React Native应用程序中,我传递了一个使用onPress函数呈现按钮的组件。 按下此按钮后,应将用户带到网页上以查看一些信息。 单击按钮后,按钮不再起作用,而是触发并引导用户进入网页而没有被单击。 我不确定为什么会这样,希望获得一些见解。

这是按钮的来源。

按钮组件

1
2
3
4
5
6
7
8
9
10
11
12
13
class Button extends Component {
  constructor(props) {
      super(props);
  }

  render() {
    return (
      <TouchableOpacity onPress={this.props.onPress()} style={styles.cardButtonWrap}>
          <Text style={styles.cardButton}>Button</Text>
      </TouchableOpacity>
    );
  }
}

专辑详情

在此调用Button组件。

1
2
3
4
5
6
7
8
9
10
11
class AlbumDetail extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    return(
<Button onPress={() => Linking.openURL(this.props.album.url)} />
    );
  }
}


您正在onPress内部调用该函数。 请改用以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
class Button extends Component {
  constructor(props) {
      super(props);
  }

  render() {
    return (
      <TouchableOpacity onPress={this.props.onPress} style={styles.cardButtonWrap}>
          <Text style={styles.cardButton}>Button</Text>
      </TouchableOpacity>
    );
  }
}