javascript - 调用函数 onPress React Native

标签 javascript reactjs react-native

我只想知道如何调用函数onPress。我已经像这样设置了我的代码:

export default class Tab3 extends Component {
    constructor(props) {
        super(props);
        this.state = {myColor: "green"};
    }

    handleClick = () => {
        if (this.state.color === 'green'){
           this.setState({myColor: 'blue'});
        } else {
           this.setState({myColor: 'green'});
        }
    }

    render() {
     return(
      <View>
           <Icon
            name='heart'
            color={this.state.myColor}
            size= {45}
            style={{marginLeft:40}}
            onPress={() => handleClick(this)}                                 
            />
      </View>
      )};

但是当我尝试这个时,我得到了错误,找不到变量 handleClick

请帮忙。我只想知道如何将函数绑定(bind)到点击事件。

最佳答案

在渲染中,您设置的处理程序不正确,请尝试一下;

 <View>
       <Icon
        name='heart'
        color={this.state.myColor}
        size= {45}
        style={{marginLeft:40}}
        onPress={this.handleClick}                                 
        />
  </View>

您使用的语法对于声明匿名函数内联或其他内容是有意义的,但由于您的处理程序是在类上定义的,您只需使用 this.functionName 引用它(而不是调用它)在 Prop 中。

关于javascript - 调用函数 onPress React Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45552957/

相关文章:

javascript - 在 meteor 中有没有一种方法可以访问空格键中的数组索引

react-native - axios post 请求 react-native 中的网络错误

react-native - 如何修复未找到的 React/RCTBridgeDelegate.h' 文件

javascript - 使用 jQuery 将箭头键绑定(bind)到导航

javascript - 将警报消息转换为弹出窗口

javascript - WordPress 使用 AJAX 加载更多帖子

reactjs - node-sass-chokidar 只会将一个文件夹而不是一个文件输出到我的 src 目录中

meteor - Semantic UI 和 ReactJS、Meteor JS、无限滚动在可见性中不调用 onBottomVisible()

reactjs - 我们可以通过 API 使用 Json 数据使用 React-Table 显示大约 100000 行吗?

react-native - RCTBridge 需要 dispatch_sync 来加载 RCTDevLoadingView