handleButtonPress
当不需要参数时,该函数在以下示例中起作用...
import React, { Component } from 'react';
import {View, Text, TouchableOpacity} from 'react-native';
export default class MyComponent extends Component {
constructor(props){
super(props)
this.state = {message:"HELLO"}
this.myFunc = this.myFunc.bind(this)
this.handleButtonPress = this.handleButtonPress.bind(this)
}
render(){
return (
<View>
<Text>{this.state.message}</Text>
<TouchableOpacity onPress={this.handleButtonPress}>
<Text>Press Me</Text>
</TouchableOpacity>
</View>
)
}
handleButtonPress(){
console.log("BUTTON WAS PRESSED")
this.myFunc()
}
myFunc(){
console.log("MY FUNCTION WAS CALLED")
this.setState({message:"GOODBYE"})
}
}
但在需要参数时在以下示例中不起作用:
render(){
return (
<View>
<Text>{this.state.message}</Text>
<TouchableOpacity onPress={function(){ this.handleButtonPress("GOODBYE") }}>
<Text>Press Me</Text>
</TouchableOpacity>
</View>
)
}
handleButtonPress(message){
console.log("BUTTON WAS PRESSED WITH MESSAGE: " + message)
this.myFunc(message)
}
myFunc(message){
console.log("MY FUNCTION WAS CALLED")
this.setState({message:message})
}
它抛出:undefined is not a function (evaluating 'this.handleButtonPress("GOODBYE")')
我一直在使用的一种策略是在handleButtonPress
函数内部再次引用该render
函数,如下所示:
render(){
handlePress = this.handleButtonPress;
return (
<View>
<Text>{this.state.message}</Text>
<TouchableOpacity onPress={function(){ handlePress("GOODBYE") }}>
<Text>Press Me</Text>
</TouchableOpacity>
</View>
)
}
但是还有另一种/更好的方法吗?