React-Native Button onPress不起作用?

时间:2018-02-20 14:48:52

标签: javascript reactjs react-native

我遇到library(lubridate) dt[, Time.Index := (year(Calendar.Data.Year.and.Quarter)-2000)*4+quarter(Calendar.Data.Year.and.Quarter)] pdt <- pdata.frame(dt , index = c("Global.Company.Key", "Time.Index")) is.pconsecutive(pdt) # <- this then reports TRUE 问题,尝试了所有解决方案并且没有onPress功能, 我也尝试过以下方法:

handleClick

我试图将功能更改为:

onPress={this.handleClick}
onPress={this.handleClick()}
onPress={this.handleClick.bind(this)}
onPress={() => this.handleClick.bind(this)}

这是我的代码:

handleClick(){
   console.log('Button clicked!');
}

这是我的Buttom.js文件:

import React, { Component } from 'react';
import {
  View,
} from 'react-native';

import Card from './common/Card';
import CardItem from './common/CardItem';
import Buttom from './common/Buttom';
import Input from './common/Input';

export default class LoginForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      email: '',
      password: '',
    }
  }

  onLoginPress() {
    //console.log(`Email is : ${ this.state.email }`);
    //console.log(`Password is : ${ this.state.password }`);
  };

  handleClick = () => {
    console.log('Button clicked!');
  };

  render() {
    return (
      <View >
        <Card>

          <CardItem>
              <Input
                  label='Email'
                  placeholder='Enter your email'
                  secureTextEntry={false}
                  onChangeText = { (email) => this.setState({ email })}
              />
          </CardItem>

          <CardItem>
              <Input
                  label='Password'
                  placeholder='Enter your password'
                  secureTextEntry={true}
                  onChangeText = { (password) => this.setState({ password })}
              />
          </CardItem>

          <CardItem>
            <Buttom onPress={this.handleClick}> Login </Buttom>
          </CardItem>

        </Card>
      </View>
    );
  }
}

2 个答案:

答案 0 :(得分:3)

您无法将事件绑定到Component。事件只能附加到React-Native中的React Native元素或仅React中的DOM。

你应该传递事件处理程序,

<Buttom onPressHanlder={this.handleClick}> Login </Buttom>

Buttom组件中使用props.onPressHanlder来调用传递的事件处理程序:

const Buttom = (props) => {
  return(
    <TouchableOpacity style={styles.ButtomView} onPress={props.onPressHanlder}>
                                                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

      <Text style={styles.TextButtom}> {props.children} </Text>
    </TouchableOpacity>
  );
}

答案 1 :(得分:1)

将函数绑定到范围

constructor(props) {
    super(props);
    this.state = {
      email: '',
      password: '',
    }
    this.handleClick = this.handleClick.bind(this);
  }

他们<Buttom onPress={() => this.handleClick() }> Login </Buttom>