反应原生 TouchableOpacity onPress 问题 [英] React native TouchableOpacity onPress Problems

查看:60
本文介绍了反应原生 TouchableOpacity onPress 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的图标按钮,如下所示:

I have a simple icon button as follows :

class SideIcon extends Component {
  render() {
    return (
      <TouchableOpacity onPress={console.log('puff')} style={styles.burgerButton}>
        <Icon name="bars" style={styles.burgerIcon}/>
      </TouchableOpacity>
    );
  }
}

它是从以下组件调用的:

It's called from the following component :

export default test = React.createClass({
  getInitialState: function() {
    return {
      isModalOpen: false
    }
  },

  _openModal() {
    this.setState({
      isModalOpen: true
    });
  },

  _closeModal() {
    this.setState({
      isModalOpen: false
    });
  },
  render() {
    return (
     <View style={styles.containerHead} keyboardShouldPersistTaps={true}>
     **<SideIcon openModal={this._openModal} closeModal={this._closeModal} />**
      <Text style={styles.logoName}>DareMe</Text>
      <SideBar isVisible={this.state.isModalOpen} />
     </View>
    );
  }
});

但是 TouchableOpacity 上的 onPress 永远不起作用.我哪里错了?虽然它在组件加载期间显示控制台语句.

But the onPress on the TouchableOpacity never works. Where I'm going wrong ? Although It shows console statements during the component load.

推荐答案

你应该绑定一个调用你的代码的函数.

You should bind a function that invokes your code.

例如:

<TouchableOpacity onPress={() => console.log('puff')} style={styles.burgerButton}>
  <Icon name="bars" style={styles.burgerIcon}/>
</TouchableOpacity>

更好的方法是给它一个组件函数的引用

A better way is to give it a reference to a component function

class SideIcon extends Component {
  handleOnPress = () => {
    console.log('puff')
  }
  render() {
    return (
      <TouchableOpacity onPress={this.handleOnPress} style={styles.burgerButton}>
        <Icon name="bars" style={styles.burgerIcon}/>
      </TouchableOpacity>
    );
  }
}

这篇关于反应原生 TouchableOpacity onPress 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆