![](/img/trans.png)
[英]Calling a callback function from different component onPress in different Component React Native JS
[英]Calling onPress on custom component in React Native
如何解决呢? 我的ModalScreen中包含一个自定义的Button组件。 似乎一切正常,但是onPress函数起作用了。 它似乎由于某种原因失去了作用域,因此我无法引用this
,甚至无法向该函数添加参数。 我在这里想念什么?
import React from 'react';
import {
Text,
View,
} from 'react-native';
import Styles from 'app/constants/Styles';
import Button from 'app/components/Button';
export default class ModalScreen extends React.Component {
onBtnPress() {
console.log('dfsdfsdf'); /// << this gets consoled out just fine
//this.props.navigation.navigate('Main'); <<<< this won't work
}
render() {
return (
<View style={Styles.center}>
<Text>MOdalScreen</Text>
<Button label='Gå vidare' onPress={ this.onBtnPress }/>
</View>
);
}
}
Button.js
import React, { Component } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import Styles from 'app/constants/Styles'
import Vars from 'app/constants/Vars'
export default class Button extends Component {
render() {
return (
<TouchableOpacity style={[Styles.round, Styles.primaryBackground]} onPress={this.props.onPress}>
<Text style={[Styles.label, Styles.textCenter, { margin: Vars.spacing.narrow }]}>
{this.props.label}
</Text>
</TouchableOpacity>
)
}
}
您是对的,它失去了范围。 您只需要以某种方式将范围绑定到handle函数,然后再将其提供给Button组件即可。 一种流行的方法是使用方便的箭头功能:
<Button label='Gå vidare' onPress={ () => this.onBtnPress() }/>
或者您可以在构造函数中使用bind:
export default class ModalScreen extends React.Component {
constructor(props) {
super(props);
this.onBtnPress = this.onBtnPress.bind(this)
}
onBtnPress() {
console.log('dfsdfsdf'); /// << this gets consoled out just fine
//this.props.navigation.navigate('Main'); <<<< this won't work
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.