React Native + Redux:一个加密货币追踪器应用
以下是一个简化的React Native加Redux的代码实例,展示了如何创建一个加密货币追踪器组件:
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { connect } from 'react-redux';
class CryptoTracker extends Component {
render() {
const { cryptoCurrency } = this.props;
return (
<View style={styles.container}>
<Text style={styles.text}>{cryptoCurrency.name}</Text>
<Text style={styles.text}>{cryptoCurrency.price}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
margin: 10,
padding: 10,
backgroundColor: '#fff',
},
text: {
fontSize: 16,
textAlign: 'center',
}
});
const mapStateToProps = (state, ownProps) => {
const cryptoCurrency = state.cryptoCurrencies.find(
currency => currency.id === ownProps.currencyId
);
return { cryptoCurrency };
};
export default connect(mapStateToProps)(CryptoTracker);
这个例子中,我们创建了一个名为CryptoTracker
的组件,它接收一个currencyId
属性,通过Redux的connect
函数将对应的加密货币信息从全局状态映射到组件的cryptoCurrency
属性。然后,组件渲染加密货币的名称和价格。mapStateToProps
函数用于查找与组件对应的加密货币信息。
评论已关闭