React Native Touchable Opacity功能

时间:2018-06-03 21:42:05

标签: javascript reactjs react-native

我的React Native应用程序中有两个函数,我需要我的TouchableOpacity才能在按下时调用它们。为此,我尝试在onPress方法中使用箭头函数,其中包含两个函数,但这不起作用。我认为这与范围有关,但我不确定。单独传递给onPress方法时,这两个函数都能正常工作。这是代码(为了便于阅读我已经修剪了很多)请帮助。

export class CreateItem extends React.Component {
constructor(props){
    super(props);
}

sendData = () => {
    itemData = this.state.item;
    this.props.action(itemData); //the action function alters the parent state (this function works fine every other time)
}
render(){
return(
    <TouchableOpacity
    onPress={() => {
    this.sendData;
    this.props.hide; //This function is passed from the parent and works fine in other scenarios 
    }}
    >
        <Text>Add Item</Text>
    </TouchableOpacity>
)
}

1 个答案:

答案 0 :(得分:2)

你错过了函数的括号

export class CreateItem extends React.Component {
constructor(props){
    super(props);
}

sendData = () => {
    itemData = this.state.item;
    this.props.action(itemData); //the action function alters the parent state (this function works fine every other time)
}
render(){
    return(
        <TouchableOpacity
            onPress={() => {
                this.sendData();
                this.props.hide(); //This function is passed from the parent and works fine in other scenarios 
            }}
        >
            <Text>Add Item</Text>
        </TouchableOpacity>
    )
}