调用函数onPress React Native

时间:2017-08-07 17:56:46

标签: 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>
      )};

但是当我尝试这个时,我会收到can't find variable handleClick

的错误

请帮忙。我只想知道如何将函数绑定到click事件。

5 个答案:

答案 0 :(得分:6)

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

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

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

答案 1 :(得分:2)

您需要使用this关键字引用该方法。

 <Icon
    onPress={this.handleClick}                                 
  />

答案 2 :(得分:1)

聚会晚了一点,但是只是想在有人需要的时候把它留在这里

export default class mainScreen extends Component {

handleClick = () => {
 //some code
}

render() {
 return(
  <View>
       <Button
        name='someButton'
        onPress={() => {
            handleClick(); //usual call like vanilla javascript 
         }}                                 
        />
  </View>
  )};

答案 3 :(得分:0)

您也可以尝试这种绑定方式

this.handleClick = this.handleClick.bind(this) 

并将其置于构造函数中。并且在调用时使用此语法

onPress = {this.handleClick}

这肯定会解决您的问题。

答案 4 :(得分:0)

如果您不使用类组件,则只需删除 this

此功能可以处理任何路线的导航(只要有一个以名称作为参数传递的屏幕),就不需要多个处理程序。

const navigation = useNavigation(); 

function handleNavigation(route) {
    navigation.navigate(route);
}

按钮将如下所示:

<Button onPress={() => handleNavigation("Menu")} ></Button>