dre*_*val 4 javascript reactjs react-native
我在我的项目中使用 react-navigation,我需要在右标题按钮单击时切换模式。当我 setState 为 true 时,我得到未定义。
代码:
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { ToggleDrawer, ToggleAdditional } from '../../utils';
import { AdditionalModal } from '../../components';
class Settings extends Component {
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return {
headerTitle: 'Profile',
headerLeft: <ToggleDrawer pressHandler={() => navigation.openDrawer()} />,
headerRight: (
<ToggleAdditional pressHandler={() => params.handleAdditionalModal()} />
)
};
};
constructor(props) {
super(props);
this.state = {
modalIsVisible: false
};
}
componentDidMount() {
const { navigation } = this.props;
navigation.setParams({
handleAdditionalModal: this.toggleAdditionalModal
});
}
toggleAdditionalModal() {
this.setState({
modalIsVisible: true
});
}
render() {
const { modalIsVisible } = this.state;
return (
<View>
<Text>Settings</Text>
<AdditionalModal isVisible={modalIsVisible} />
</View>
);
}
}
export default Settings;
Run Code Online (Sandbox Code Playgroud)
我做错了什么,在 react-navigation 标头中处理此类点击事件的最佳方法是什么?
谢谢!
尝试使用箭头函数 toggleAdditionalModal
toggleAdditionalModal = () =>{
this.setState({
modalIsVisible: true
});
}
Run Code Online (Sandbox Code Playgroud)
你需要箭头函数,因为你想访问this属性,它指的是当前类。
箭头函数意味着this不会引用函数的上下文,而是引用类的上下文。
| 归档时间: |
|
| 查看次数: |
1439 次 |
| 最近记录: |