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")')
1つの戦略はhandleButtonPress
functiを参照することですこのように、再び内部render
機能、上:
render(){
handlePress = this.handleButtonPress;
return (
<View>
<Text>{this.state.message}</Text>
<TouchableOpacity onPress={function(){ handlePress("GOODBYE") }}>
<Text>Press Me</Text>
</TouchableOpacity>
</View>
)
}
だが、別の/より良い方法はありますか?
無名関数内の 'this'がそれを混乱させました。 – Li357
もしあなたがそれがそうでなければならないと言っているならば: 'onPress = {function(){handleButtonPress(" GOODBYE ")}}' ... throws: '変数を見つけることができません:handleButtonPress' – s2t2