gpt4 book ai didi

reactjs - MobX 和 React Native 功能组件 : How can we implement mobX in React Native Functional Component?

转载 作者:行者123 更新时间:2023-12-05 09:34:24 25 4
gpt4 key购买 nike

下面的代码只是我在网上找到的一个例子。

import { observable, computed } from "mobx";
import { observer } from "mobx-react";
import React from "react";
import { SafeAreaView, Text, TextInput, StyleSheet } from "react-native";
@observer
class Shop extends React.Component {
@observable price = 9;
@observable quantity = 11;
@computed get total() {
return this.price * this.quantity;
}
render() {
return (
<SafeAreaView style={styles.container}>
<Text>Price: </Text>
<TextInput value={this.price} onChangeText={value => { this.price = value }} />
<Text>Quantity: </Text>
<TextInput value={this.quantity} onChangeText={value => { this.quantity = value }} />
<Text>Total (Price and Quantity): {this.total}</Text>
</SafeAreaView>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
})

可悲的是,我在网上找到的大多数关于 React Native 中的 MobX 的例子都是用于类组件。

有人可以将此代码转换为功能组件吗?

谢谢

最佳答案

这里有一些关于如何在功能组件中使用它的想法。 (注意,我没有测试代码,但这是给你指明方向的)

<强>1。为 Shop Store 创建一个类,它应该是这样的。

import { observable, computed, action } from "mobx";

export class ShopStore {

@observable price;
@observable quantity;

constructor (value) {
this.id = 9;
this.quantity = 11;
}

@computed get total() {
return this.price * this.quantity;
}

// Use @action to modify state value
@action setPrice = (price) => {
this.price = price;
}

// Use @action to modify state value
@action setQuantity = (quantity) => {
this.quantity = quantity;
}
}

<强>2。在您的 App.js 中初始化 Mobx 商店

import React from 'react';
import { ShopStore } from './src/mobx/store';
import ShopComponent from "./src/components/ShopComponent";
function App() {
const store = new ShopStore()
return (
<ShopComponent store={store}/>
);
}
export default App;

<强>3。将 mobx 观察者连接到功能组件

import { observable, computed } from "mobx";
import { observer } from "mobx-react";
import React from "react";
import { SafeAreaView, Text, TextInput, StyleSheet } from "react-native";

function ShopComponent(props) {

const { setPrice, setQuantity } = props.store

return(
<SafeAreaView style={styles.container}>
<Text>Price: </Text>
<TextInput value={props.store.price} onChangeText={value => { setPrice(value) }} />
<Text>Quantity: </Text>
<TextInput value={props.store.quantity} onChangeText={value => { setQuantity(value) }} />
<Text>Total (Price and Quantity): {props.store.total() }</Text>
</SafeAreaView>
)
}
export default observer(ShopComponent);

关于reactjs - MobX 和 React Native 功能组件 : How can we implement mobX in React Native Functional Component?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66665732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com