为什么onpress函数在react native中不起作用



类文件

export class salon extends Component {
constructor(props) {
super(props);
this.state = {
status : true,
};  
}
_toggleModal(){
Alert.alert('hello');
}
}

我正在侧边栏中使用导航选项

我在可触摸的不透明度中添加了onpress功能,它不能仅在触摸时工作

<TouchableOpacity onPress={() =>  {this._toggleModal}}>
</TouchableOpacity>

您应该将函数绑定到构造函数或正在使用中。

在构造函数中:

export class salon extends Component {
constructor(props) {
super(props);
this.state = {
status : true,
};  
this._toggleModal = this._toggleModal.bind(this);
}
_toggleModal(){
Alert.alert('hello');
}
}

使用中:

<TouchableOpacity 
onPress={() =>  {this._toggleModal.bind(this)}}>
</TouchableOpacity>

查看文档以了解更多信息。

您可以使用类似onPress={() => {this._toggleModal()}}的箭头函数来完成

尝试调用没有箭头函数的函数,如下所示:onPress={this._toggleModal

最新更新