RN代码片段

// 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(),
        // ...
    }
}

复制代码

转载于:https://juejin.im/post/5c6282f46fb9a049e702971d

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值