我有以下代码,其中onPress我希望调用一个函数。
class BarButton extends Component {
render() {
const {imageUri,onPress} = this.props;
return (
<TouchableOpacity style={styles.buttonStyle}
onPress={() => onPress()}
>
<Image source={imageUri} style = {styles.buttonStyle}/>
</TouchableOpacity>
);
}
}
BarButton.propTypes = {
onPress: PropTypes.func.isRequired,
imageUri:PropTypes.string.isRequired
};
export default class ShopScreen extends Component {
static navigationOptions = {
title: 'Shop',
headerRight: <BarButton imageUri={require('./images/filter.png')} onPress={ this.onPressButton}/>,
headerTintColor:'black'
};
constructor(props){
super(props);
this.state ={ isLoading: true}
this.onPressButton = this.onPressButton.bind(this);
}
onPressButton()
{
this.props.navigation.navigate('Filter');
}
所以我想调用函数onPressButton并导航到下一个屏幕,在此我得到错误
答案 0 :(得分:0)
您可以使用navigation
在使用函数而不是对象时收到的navigationOptions
对象。
static navigationOptions = ({ navigation }) => {
return {
title: 'Shop',
headerRight: (
<BarButton
imageUri={require('./images/filter.png')}
onPress={() => navigation.navigate('Filter')}
/>
),
headerTintColor:'black'
};
};
答案 1 :(得分:0)
基本上作为一个新手,我没有理解navigationOptions是一个静态变量因此无法使用&#34;这个&#34;引用任何东西,以下线程提出了许多解决方案,这里是原始链接,并且在所有为我工作的如下,在这里发布它是为了方便(适当归功于原作者https://github.com/jacse)
https://github.com/react-navigation/react-navigation/issues/145
class MyScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return {
headerRight: <Button title="Save" onPress={() => params.handleSave()} />
};
};
_saveDetails = () => {
console.log('clicked save');
console.log('clicked save ' + this.state.xxxxxx);
}
componentDidMount() {
this.props.navigation.setParams({ handleSave: this._saveDetails });
}
render() {
return (
<View />
);
}
}
&#13;