我只是尝试mobx,我有一个简单的组件和一个商店。每当按下按钮时,我希望它的文本将使用新的时间戳进行更新。但是,这不会发生,我也不知道为什么。这是代码:
import React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
import { Card, Button } from 'react-native-paper';
import { observer } from "mobx-react";
import { makeAutoObservable } from "mobx"
class State {
timestamp = Date.now();
constructor() {
makeAutoObservable(this)
}
setTimestamp() {
this.timestamp = Date.now();
}
}
const state = new State();
const App = observer(() => {
const { timestamp, setTimestamp } = state;
return (
<View style={s.root}>
<Button onPress={setTimestamp}>
{timestamp}
</Button>
</View>
);
});
const s = StyleSheet.create({
root: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8
}
});
export default App;
也可以在这里找到:https : //snack.expo.io/@pavermakov/react-native-mobx
我使用以下依赖项:
"mobx": "6.0.1",
"mobx-react": "7.0.0"
我想念什么吗?
使用这段代码:
<Button onPress={setTimestamp}>
您正在丢失类实例的this
上下文State
。单击按钮时this
实际上指的是Button
元素,因此没有Button.timestamp
更改。解决这个问题的最简单方法是bind
在setTimestamp
回state
这样的类:
<Button onPress={setTimestamp.bind(state)}>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句