RN程式碼片段

bainian發表於2019-02-14
// listview
const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.state = { dataSource: ds.cloneWithRows([{ image: '', title: '', }, { image: '', title: '', }]) };

<ListView dataSource={this.state.dataSource}
    renderRow={this._renderRow}
    renderSeparator={this._renderSeperator}
    refreshControl={this._renderRefreshControl} />

_renderSeperator = (sectionId, rowId, adjacentRowHighlighted) => { return (<View key={`${sectionId}-${rowId}`} style={styles.divider}></View>); };

_renderRefreshControl = () => {
    return (<RefreshControl
        refreshing={this.state.isRefreshing}
        tintColor='#dfd'
        title='title'
        titleColor='#ddd' />);
};

// Array應用
const products = Array.from(new Array(10)).map((value, index) => ({
    image: require('./images/img1.png'),
    title: `New product ${index}`,
}));
this.setState({ isRefresh: false, dataSource: ds.cloneWithRows(products) });

//引數傳遞
return <Component {...route.params} navigator={navigator} />
const { navigator } = this.props;
navigator.push({ name: 'detail', component: Detail, params: { productName: 'detailname', productTitle: 'detailtitle' } });
// this.props.productTitle

// Screen.js
import { PixelRatio, Dimensions } from 'react-native';

export default {
    'width': Dimensions.get('window').width,
    'height': Dimensions.get('window').height,
    'pixelRatio': PixelRatio.get(),
    'resolutionX': Dimensions.get('window').width * PixelRatio.get(),
    'resulutionY': Dimensions.get('window').height * PixelRatio.get(),
}

import Screen from 'Screen';
console.log('width = ', Screen.width);

// 轉換為int
width: parseInt(this.props.width);

// Animation
// requestAnimationFrame
_startAnimatin = () => {
    let count = 0;
    while (+count < 1000) {
        requestAnimationFrame(() => {
            this.setState({
                width: this.state.width + 1,
                height: this.state.height + 1
            });
        });
    }
}

// LayoutAnimation
_startAnimatin = () => {
    LayoutAnimation.configureNext({
        duration: 1000,
        create: {
            type: LayoutAnimation.Types.spring,
            property: LayoutAnimation.Properties.scaleXY,
        },
        update: {
            type: LayoutAnimation.Types.spring,
        }
    });
    this.setState({
        width: this.state.width + 100,
        height: this.state.height + 100
    });
}

//Animated
// Animated 動畫支援 Animated.Text, Animated.Image, Animated.View
constructor(props) {
    super(props);
    this.state = {
        bounceValue: new Animated.Value(0) // 初始縮放為0
    };
}

<Animated.View style={[styles.animation, {
    width: this.state.width,
    height: this.state.height,
    transform: [{ scale: this.state.bounceValue }]
}]} ></Animated.View>

_startAnimatin = () => {
    Animated.spring(this.state.bounceValue, { toValue: 1 }).start() // spring, decay, timing
}

componentDidMount() {
    this._startAnimatin();
}

return (
    <View>
        <Animation width='200' height='200'></Animation>
    </View>
);

_startAnimatin = () => {
    Animated.parallel([  // 並行動畫
        Animated.spring(this.state.bbounceValue, { toValue: 1 }),
        Animated.timing(this.state.rotateValue, {
            toValue: 1,
            duration: 800,
            easing: Easing.out(Easing.quad) // 漸變函式
        }),
    ]);
};

// AppState
AppState.addEventListener('change', this._handleAppStateChange); // 發生change事件時回撥方法
AppState.removeEventListener('change', this._handleAppStateChange);

_handleAppStateChange = (nextAppState) => {
    if (nextAppState === 'inactive' || nextAppState === 'background') {
        console.log('enter background');
    } else if (nextAppState === 'active') {
        console.log('enter foreground');
    }
}

BackAndroid.addEventListener('hardwareBackpress', this._onBackAndroid);

_onBackAndroid = () => {
    alert('back click');
    return true; // true 表示已處理,不然會繼續走預設處理
}

// datePicker
_showDatePicker = async () => {
    let newState = {};
    const { action, year, month, day } = await DatePickerAndroid.open();
    if (action === DataPickerAndroid.dismissdAction) {
        newState['dateText'] = 'cancel back';
    } else {
        let date = new Date(year, month, day);
        newState['dataText'] = date.toLocaleDateString();
    }
}

// 位置Geolocation
// <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
import Geolocation from 'Geolocation';
_fetchLocation = () => {
    Geolocation.getCurrentPosition((data) => {
        alert('get locatin suc = ', JSON.stringify(data));
    }, () => {
        alert('get location fail = ')
    });
}

// keyboard
this.keyboardshowlistener = Keyboard.addListener('keyboardDidShow', () => { this.setState({ keyboardText: 'keyboard pop out' }) });
this.keyboardhidelistener = Keyboard.addListener('keyboardDidHide', () => { this.setState({ keyboardText: 'keyboard hide' }) });
this.keyboardhidelistener.remove();
this.keyboardshowlistener.remove();

// 聯網狀態
// <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
this.state = { connectionInfo: '' };

NetInfo.addEventListener('change', this._handlerConnectInfoChange);
NetInfo.fetch().done((connectionInfo) => { this.setState({ connectionInfo }) });
console.log('current connect type: ', this.state.connectionInfo);
NetInfo.removeEventListener('change', this._handlerConnectInfoChange);
_handlerConnectInfoChange = (connectionInfo) => {
    this.setState({ connectionInfo });
}

// 許可權設定 PermissionAndroid
// <uses-permission android:name="android.permission.CAMERA" />
this.state = {
    permission: PermissionsAndroid.PERMISSIONS.CAMERA,
    hasPermission: 'not found',
};
_requestPermission = async () => {
    let result = await PermissionsAndroid.request(this.state.permission, { title: '許可權申請', message: '申請攝像許可權了' });
    this.setState({ hasPermission: result });
}

// Toast 提示框 ToastAndroid
_onBackAndroid = () => {
    if (this.state.lastBackPressed && this.lastBackPressed + 2000 >= Date().now()) {
        return false; // 2秒內
    }
    this.lastBackPressed = Date.now();
    ToastAndroid.show('再按一次退出應用', ToastAndroid.SHORT);
    return true;
}

// 與原生互動
// DeviceInfo.js
export default { // 匯出一個普通的模組
    'systemName': 'unknow value',
    'systemVersion': 'unknow',
    'defaultLanguage': 'unknow',
    'appVersion': 'unknow',
}
//Text.js
import DeviceInfo from './DeviceInfo';
console.log('DeviceInfo = ', DeviceInfo.appVersion);

public class DeviceInfoModule extends ReactContextBaseJavaModule {
    public DeviceInfoModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return "DeviceInfo";
    }

    @ReactMethod
    public Map<String, Object> getContants() {
        HashMap < String, Object > constants = new HashMap();
        constants.put('systemName', 'Android');
        constants.put('systemVersion', '9.0');
        constants.put('defaultLanguage', 'zh');
        constants.put('appVersion', '1.0');
        return constants;
    }
}

public class DeviceInfoPackage implements ReactPackage {
    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    @Override
    public List<NativeModule> createNativeModules(
        ReactApplicationContext reactContext) {
        List < NativeModule > modules = new ArrayList<>();
        modules.add(new DeviceInfoModule(reactContext));
        return modules;
    }
}

public class MainApplication extends NavigationApplication {

    protected List<ReactPackage> getPackages() {
        // ...
        new DeviceInfoPackage(),
        // ...
    }
}

複製程式碼

相關文章