哭唧唧,在github上面找react-native學習,多麼貧瘠的英文知識哇這個就是我
我甚至不知道這個項目運作出來了的意義,不過一個一個學習哇
不積跬步無以至千裡,加油哇~~
在浏覽器中,我們找到這個項目
https://github.com/futurice/pepperoni-app-kit
使用下面方式運作
git clone https://github.com/futurice/pepperoni-app-kit.git
cd pepperoni-app-kit
yarn install
react-native run-ios/react-native run-android
我們首先可以看項目的效果
![]
看Index.js我們可以看到有使用redux和react-react-native
import {Provider} from 'react-redux';
import store from './src/redux/store';
import AppViewContainer from './src/modules/AppViewContainer';
import React, {Component} from 'react';
import {AppRegistry} from 'react-native';
class PepperoniAppTemplate extends Component {
render() {
return (
<Provider store={store}>
<AppViewContainer />
</Provider>
);
}
}
AppRegistry.registerComponent('PepperoniAppTemplate', () => PepperoniAppTemplate);
打開檔案,我們可以看到項目的目錄

接下來我們一步一步分析
//navigator.js
import {Platform} from 'react-native';
import {TabNavigator, StackNavigator} from 'react-navigation';
import CounterViewContainer from '../counter/CounterViewContainer';
import ColorViewContainer from '../colors/ColorViewContainer';
// headerColor控制的是背景色
// activeColor控制的是選中的顔色
const headerColor = '#39babd';
const activeColor = 'red';
// TabNavigator is nested inside StackNavigator
// 從元件react-navigation中取得 TabNavigator
export const MainScreenNavigator = TabNavigator({
//定義兩個元件counter和color元件
Counter: {screen: CounterViewContainer},
Color: {screen: ColorViewContainer}
}, {
tabBarOptions: {
...Platform.select({
android: {
activeTintColor: activeColor,
indicatorStyle: {backgroundColor: activeColor},
style: {backgroundColor: headerColor}
}
})
}
});
MainScreenNavigator.navigationOptions = {
title: 'Pepperoni App Template',
headerTitleStyle: {color: 'white'},
headerStyle: {
backgroundColor: headerColor,
elevation: 0 // disable header elevation when TabNavigator visible
}
};
// Root navigator is a StackNavigator
//定義初始化的頁面為MainScreenNavigator
const AppNavigator = StackNavigator({
Home: {screen: MainScreenNavigator},
InfiniteColorStack: {screen: ColorViewContainer}
});
export default AppNavigator;
頁面如下:
與redux互動
//NavigatorViewContainer.js
import {connect} from 'react-redux';
import NavigatorView from './NavigatorView';
export default connect(
state => ({
navigatorState: state.get('navigatorState').toJS()
})
)(NavigatorView);
//NavigatorView.js
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {addNavigationHelpers} from 'react-navigation';
import AppNavigator from './Navigator';
class NavigatorView extends Component {
static displayName = 'NavigationView';
static propTypes = {
dispatch: PropTypes.func.isRequired,
navigatorState: PropTypes.shape({
index: PropTypes.number.isRequired,
routes: PropTypes.arrayOf(PropTypes.shape({
key: PropTypes.string.isRequired,
routeName: PropTypes.string.isRequired
}))
}).isRequired
};
render() {
return (
<AppNavigator
navigation={
addNavigationHelpers({
dispatch: this.props.dispatch,
state: this.props.navigatorState
})
}
/>
);
}
}
export default NavigatorView;
我們來看
//CounterView.js
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {
StyleSheet,
TouchableOpacity,
Image,
Text,
View
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
class CounterView extends Component {
//定義靜态元件
static displayName = 'CounterView';
static navigationOptions = {
title: 'Counter',
tabBarIcon: (props) => (
<Icon name='plus-one' size={24} color={props.tintColor} />
)
}
//靜态屬性
static propTypes = {
counter: PropTypes.number.isRequired,
userName: PropTypes.string,
userProfilePhoto: PropTypes.string,
loading: PropTypes.bool.isRequired,
counterStateActions: PropTypes.shape({
increment: PropTypes.func.isRequired,
reset: PropTypes.func.isRequired,
random: PropTypes.func.isRequired
}).isRequired,
navigate: PropTypes.func.isRequired
};
// 點選增加的方法
increment = () => {
this.props.counterStateActions.increment();
};
// 清除
reset = () => {
this.props.counterStateActions.reset();
};
// 随機數
random = () => {
this.props.counterStateActions.random();
};
//跳轉到另一個頁面
bored = () => {
this.props.navigate({routeName: 'Color'});
};
renderUserInfo = () => {
if (!this.props.userName) {
return null;
}
return (
<View style={styles.userContainer}>
<Image
style={styles.userProfilePhoto}
source={{
uri: this.props.userProfilePhoto,
width: 80,
height: 80
}}
/>
<Text style={styles.linkButton}>
Welcome, {this.props.userName}!
</Text>
</View>
);
};
render() {
//點選随機數的那個背景色會loading變紅色
const loadingStyle = this.props.loading
? {backgroundColor: 'red'}
: null;
return (
<View style={styles.container}>
{this.renderUserInfo()}
<TouchableOpacity
accessible={true}
accessibilityLabel={'Increment counter'}
onPress={this.increment}
style={[styles.counterButton, loadingStyle]}>
<Text style={styles.counter}>
{this.props.counter}
</Text>
</TouchableOpacity>
<TouchableOpacity
accessible={true}
accessibilityLabel={'Reset counter'}
onPress={this.reset}>
<Text style={styles.linkButton}>
Reset
</Text>
</TouchableOpacity>
<TouchableOpacity
accessible={true}
accessibilityLabel={'Randomize counter'}
onPress={this.random}>
<Text style={styles.linkButton}>
Random
</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.bored} accessible={true}>
<Text style={styles.linkButton}>
{'I\'m bored!'}
</Text>
</TouchableOpacity>
</View>
);
}
}
//一種新式寫法,定義一個circle
const circle = {
borderWidth: 0,
borderRadius: 40,
width: 80,
height: 80
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white'
},
userContainer: {
justifyContent: 'center',
alignItems: 'center'
},
//這裡的是...circle擴充這個屬性,厲害的寫法哇
userProfilePhoto: {
...circle,
alignSelf: 'center'
},
counterButton: {
...circle,
backgroundColor: '#349d4a',
alignItems: 'center',
justifyContent: 'center',
margin: 20
},
counter: {
color: 'white',
fontSize: 20,
textAlign: 'center'
},
welcome: {
textAlign: 'center',
color: 'black',
marginBottom: 5,
padding: 5
},
linkButton: {
textAlign: 'center',
color: '#CCCCCC',
marginBottom: 10,
padding: 5
}
});
export default CounterView;
頁面效果為
//CounterState.js
//裡面定義的是state狀态
import {Map} from 'immutable';
import {loop, Effects} from 'redux-loop-symbol-ponyfill';
import {generateRandomNumber} from '../../services/randomNumberService';
// Initial state
const initialState = Map({
value: 0,
loading: false
});
// Actions
const INCREMENT = 'CounterState/INCREMENT';
const RESET = 'CounterState/RESET';
const RANDOM_REQUEST = 'CounterState/RANDOM_REQUEST';
const RANDOM_RESPONSE = 'CounterState/RANDOM_RESPONSE';
// Action creators
export function increment() {
return {type: INCREMENT};
}
export function reset() {
return {type: RESET};
}
export function random() {
return {
type: RANDOM_REQUEST
};
}
export async function requestRandomNumber() {
return {
type: RANDOM_RESPONSE,
payload: await generateRandomNumber()
};
}
// Reducer
export default function CounterStateReducer(state = initialState, action = {}) {
switch (action.type) {
case INCREMENT:
return state.update('value', value => value + 1);
case RESET:
return initialState;
case RANDOM_REQUEST:
return loop(
state.set('loading', true),
Effects.promise(requestRandomNumber)
);
case RANDOM_RESPONSE:
return state
.set('loading', false)
.set('value', action.payload);
default:
return state;
}
}
//CounterViewContainer.js
這個裡面是dispatch方法,改變state的狀态
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
//引入UI元件
import CounterView from './CounterView';
import {NavigationActions} from 'react-navigation';
//引入action
import * as CounterStateActions from '../counter/CounterState';
export default connect(
state => ({
counter: state.getIn(['counter', 'value']),
loading: state.getIn(['counter', 'loading'])
}),
dispatch => {
return {
navigate: bindActionCreators(NavigationActions.navigate, dispatch),
counterStateActions: bindActionCreators(CounterStateActions, dispatch)
};
}
)(CounterView);
//ColorView.js
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {
Button,
View,
StyleSheet
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
const color = () => Math.floor(255 * Math.random());
/**
* Sample view to demonstrate StackNavigator
* @TODO remove this module in a live application.
*/
class ColorView extends Component {
static displayName = 'ColorView';
static navigationOptions = {
title: 'Colors!',
tabBarIcon: (props) => (
<Icon name='color-lens' size={24} color={props.tintColor} />
),
// TODO: move this into global config?
headerTintColor: 'white',
headerStyle: {
backgroundColor: '#39babd'
}
}
static propTypes = {
navigate: PropTypes.func.isRequired
};
constructor(props) {
super(props);
//初始化的背景色
this.state = {
background: `rgba(${color()},${color()},${color()}, 1)`
};
}
//點選open進入新的頁面
open = () => {
this.props.navigate({routeName: 'InfiniteColorStack'});
};
//點選colors,頁面進入就顯示這個
render() {
const buttonText = 'Open in Stack Navigator';
return (
<View style={[styles.container, {backgroundColor: this.state.background}]}>
<Button color='#ee7f06' title={buttonText} onPress={this.open}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
});
export default ColorView;
項目運作效果為
當進行多次點選顔色的時候,會将狀态存儲起來
//ColorViewContainer.js
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {NavigationActions} from 'react-navigation';
import ColorView from './ColorView';
export default connect(
null,
dispatch => {
return {
navigate: bindActionCreators(NavigationActions.navigate, dispatch)
};
}
)(ColorView);
by我了解的十分淺顯,但是會繼續找項目與大家一起進步的
作者:jser_dimple