HelloJs React Native

PartII

  • ListView
  • 支援多平台
  • Geolocation
  • AsyncStorage
  • Navigator
  • react-native-router-flux

老王賣瓜

ListView

最常見的 UI

ListItem

List 是由重複的 listitem 組成的

ListView.DataSource

為ListView組件提供高性能的數據處理和訪問

constructor(props) {
  super(props);
  const ds = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 !== r2
  });
  this.state = {
    ds,
  };
}


_onDataArrived = (newData) => {
  this._data = this._data.concat(newData);
  this.setState({
    ds: this.state.ds.cloneWithRows(this._data)
  });
};

ListView

constructor(props) {
  super(props);
  var ds = new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 !== r2
  });
  this.state = {
    dataSource: ds.cloneWithRows(['row 1', 'row 2']),
  };
}

render() {
  return (
    <ListView
      dataSource={this.state.dataSource}
      renderRow={(rowData) => <Text>{rowData}</Text>}
    />
  );
}

ListView Props

  • dataSource

  • renderRow

  • initialListSize

為多平台客制

為什麼需要?

常見方案

/common/components/   
/android/components/   
/ios/components/

用資料夾區分

BigButtonIOS.js
BigButtonAndroid.js

用檔名區分

BigButton.ios.js
BigButton.android.js

React Native 解決方案

import BigButton from './components/BigButton';
import { Platform } from 'react-native';

或是使用

var styles = StyleSheet.create({
  container: {
    flex: 1,
    ...Platform.select({
      ios: {
        backgroundColor: 'red',
      },
      android: {
        backgroundColor: 'blue',
      },
    }),
  },
});

也可以回傳 Component

var Component = Platform.select({
  ios: () => require('ComponentIOS'),
  android: () => require('ComponentAndroid'),
})();

<Component />;

Geolocation

AndroidManifest.xml

新增

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  componentDidMount() {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        console.log(position);
      },
      (error) => alert(error.message),
      {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
    );
    this.watchID = navigator.geolocation.watchPosition((position) => {
      console.log(position);
    });
  }

跟 Web 很像

AsyncStorage

Navigator

Navigation Bar

<Navigator
  renderScene={(route, navigator) =>
    // ...
  }
  navigationBar={
     <Navigator.NavigationBar
       routeMapper={{
         LeftButton: (route, navigator, index, navState) =>
          { return (<Text>Cancel</Text>); },
         RightButton: (route, navigator, index, navState) =>
           { return (<Text>Done</Text>); },
         Title: (route, navigator, index, navState) =>
           { return (<Text>Awesome Nav Bar</Text>); },
       }}
       style={{backgroundColor: 'gray'}}
     />
  }
/>
  • react-native-router-flux

HelloJs

By fuyaode

HelloJs

  • 1,217