$ react-native init AwesomeProject
To run your app on iOS:
cd /path/to/project
react-native run-ios
- or -
Open ios/project.xcodeproj in Xcode
Hit the Run button
To run your app on Android:
cd /path/to/project
Have an Android emulator running (quickest way to get started), or a device connected
react-native run-androidbrew install node
brew install watchman
sudo gem install cocoapods
brew install --cask adoptopenjdk/openjdk/adoptopenjdk8# adb
export PATH=${PATH}:~/Library/Android/sdk/platform-tools
# java sdk
export JAVA_HOME=/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH
export CLASS_PATH=$JAVA_HOME/lib/tools.jar
# android home
export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools
Check by $ echo $JAVA_HOME and $ echo $CLASS_PATH.
$ react-native run-ios
Open ios project in folder ./ios.
TARGETS > General > Identity > Bundle Identifier
TARGETS > General > Signing > Team
$ react-native run-ios or click run button in Xcode
$ react-native run-android
Use $ adb devices to view connected android devices.
Add --simulator="xxx":
$ react-native run-ios --simulator="iPhone 8 Plus"
const userContext = React.createContext({user: {}});
// ...
render() {
return (
// Pass user state as value to context.Provider so it can be consumed by context.Consumer
<userContext.Provider value={this.state.user}>
<Main/>
</userContext.Provider>
);
}
// ...
function Main(props) {
return (
<Sidebar/>
<userContext.Consumer>
{(value) => (<Avatar user={value}/>);}
</userContext.Consumer>
<Content/>
)
}ios: Press Cmd+R to reload, Cmd+D or shake for dev menu
android: Double tap R on your keyboard to reload, Shake or press menu button for dev menu
You should consider using the new upgrade tool based on Git. It makes upgrades easier by resolving most conflicts automatically. To use it:
- Go back to the old version of React Native
- Run "npm install -g react-native-git-upgrade"
- Run "react-native-git-upgrade" See https://facebook.github.io/react-native/docs/upgrading.html
$ sudo ...
* What went wrong:
A problem occurred configuring project ':app'.
> SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.Add a file named local.properties to project/android/ folder and add following content:
## This file is automatically generated by Android Studio.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must *NOT* be checked into Version Control Systems,
# as it contains information specific to your local configuration.
#
# Location of the SDK. This is only used by Gradle.
# For customization when using a Version Control System, please read the
# header note.
#Fri Sep 22 16:39:17 PDT 2017
# ndk.dir=/Users/gabriel_peal/sdk/ndk-bundle
sdk.dir=/Users/tom/Library/Android/sdk
May the path above will depend on yours. Change it if not same to me.
$ npm install
project/gradle.properties
android.useDeprecatedNdk=true
> Configure project :app
WARNING: The specified Android SDK Build Tools version (28.0.2) is ignored, as it is below the minimum supported version (28.0.3) for Android Gradle Plugin 3.2.1.
Android SDK Build Tools 28.0.3 will be used.
To suppress this warning, remove "buildToolsVersion '28.0.2'" from your build.gradle file, as each version of the Android Gradle Plugin now has a default version of the build tools.
Checking the license for package Android SDK Platform 28 in /Users/tom/Library/Android/sdk/licenses
Warning: License for package Android SDK Platform 28 not accepted.
FAILURE: Build failed with an exception.
* What went wrong:
A problem occurred configuring project ':app'.
> Failed to install the following Android SDK packages as some licences have not been accepted.
platforms;android-28 Android SDK Platform 28
To build this project, accept the SDK license agreements and install the missing components using the Android Studio SDK Manager.
Alternatively, to transfer the license agreements from one workstation to another, see http://d.android.com/r/studio-ui/export-licenses.html
Using Android SDK: /Users/tom/Library/Android/sdkUse Android Studio open project/android to install missing things. And solve Android SDK Build Tools version (28.0.2) problem.
Unable to load script from assets index.android.bundle on windows
yustada commented on Mar 9, 2017
My problem has been solved by adding NSAllowsLocalNetworking to Info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSAllowsArbitraryLoadsInWebContent</key>
<true/>
<key>NSAllowsLocalNetworking</key>
<true/>
</dict>
</key>
I am not sure it is because of RN0.42 or iOS issue, but it is solved in my case.
I was able to workaround the warning by updating AppDelegate.m
#if RCT_DEV
#import <React/RCTDevLoadingView.h>
#endif
...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
RCTBridge *bridge = [[RCTBridge alloc] initWithBundleURL:jsCodeLocation
moduleProvider:nil
launchOptions:launchOptions];
#if RCT_DEV
[bridge moduleForClass:[RCTDevLoadingView class]];
#endif
RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
moduleName:@"Test"
initialProperties:nil];
...
}
AndroidManifest.xml:
<activity
...
android:windowSoftInputMode="stateAlwaysHidden|adjustPan">
...
</activity>设置android:windowSoftInputMode="stateAlwaysHidden|adjustPan"就行了。
VirtualizedList: missing keys for items, make sure to specify a key property on each item or provide a custom keyExtractor.
Basic FlatList code throws Warning - React Native
<Flatlist
//...
keyExtractor={(item, index) => index.toString()}
/>
this.props.navigation.navigate('ToPage')
//or with params
this.props.navigation.navigate('ToPage', {
title:'anything'
})
//get the param inside of ToPage's render()
const { params } = this.props.navigation.state;
<Text>title:{JSON.stringify(params.title)}</Text>
this.props.navigation.goBack()
For example:
After run $ npm i --save react-native-ble-manager, you need link by command $ react-native link
You need rebuild project to use your module.
NSNumber parameter need specify nonnull
In my test, I modal a page, in the page's componentWillMount, I console.log something, when modal the page, there will be a long stop.
const AppNavigator = createStackNavigator(
{
Home: {
screen: Home,
navigationOptions: {
header: null,
}
}
},
// ...
);From how to delete installed library form react native project:
- If it is a library based only on javascript, than you can just run
npm uninstall --save package_nameornpm uninstall --save-dev package_name - If you've installed a library with native content that requires linking, and you've linked it with rnpm then you can do:
rnpm unlink package_namethen follow step 1 - If you've installed a library with native content manually, then just undo all the steps you took to add the library in the first place. Then follow step 1.
Search package_name in project, and delete lines contain it if necessary.
add <uses-permission android:name="android.permission.CAMERA" /> to project/android/app/src/main/AndroidManifest.xml
android {
...
defaultConfig {
...
missingDimensionStrategy 'react-native-camera', 'general' <-- insert this line
}
}
Parameters: react-navigation笔记
react-native 按键事件 Android USB 扫码枪获取扫描内容 kevinejohn/react-native-keyevent android Keycode 完全对照表
// ...
import com.facebook.react.bridge.ReactContext;
import android.support.annotation.Nullable;
import android.view.KeyEvent;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.Arguments;
import java.awt.event.KeyEvent;
public class MainActivity extends ReactActivity {
// ...
private void sendEvent(ReactContext reactContext, String eventName, @Nullable WritableMap params) {
reactContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
ReactContext reactContext = getReactInstanceManager().getCurrentReactContext();
WritableMap params = Arguments.createMap();
params.putInt("keyCode", event.getKeyCode());
if (event.getAction() == KeyEvent.ACTION_DOWN) {
sendEvent(reactContext, "keydown", params);
}else if (event.getAction() == KeyEvent.ACTION_UP) {
sendEvent(reactContext, "keyup", params);
}
return super.dispatchKeyEvent(event);
}
}扫码枪是连续触发按键事件来实现的,最后以回车(keyCode=66)结尾。所以要自行拼接起来。
比如扫描barcode = 234的条码,会触发四次keydown,四次keyCode分别为:9, 10, 11, 66。
Build>Generate Signed APK...>Create new...>
打包APK Androidstudio 3.4打包并生成签名
> Task :app:bundleReleaseJsAndAssets FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':app:bundleReleaseJsAndAssets'.
> Could not list contents of '/...'. Couldn't follow symbolic link.
'Couldn't follow symbolic link' when testing release build for Android #11212
./android/gradlew --stop
Generating Release APK Fails at bundleReleaseJsAndAssets
How to return a Boolean from @ReactMethod in React Native?
In MainApplication.java:
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new CustomPackage()
);
}
<uses-permission android:name="android.permission.NFC" />
What happens when maximum storage size fills up?
When maximum size fills up, it will loop over(the 1001th will overwrite the 1st, and the 1st is gone.
Cannot add task 'wrapper' as a task with that name already exists
$ mkdir android/app/src/main/assets
$ react-native bundle --platform android --dev false --en
try-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --a
ssets-dest android/app/src/main/res
$ react-native run-android --variant=debugAdd the following code to /res/values/styles.xml
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:spinnerItemStyle">@style/SpinnerItem</item>
<item name="android:spinnerDropDownItemStyle">@style/SpinnerDropDownItem</item>
</style>
<style name="SpinnerItem" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textSize">18dp</item>
</style>
<style name="SpinnerDropDownItem" parent="Theme.AppCompat.Light.NoActionBar">
<item name="android:textColor">#ffffff</item>
<item name="android:textSize">18dp</item>
<item name="android:fontFamily">sans-serif-light</item>
<item name="android:gravity">center</item>
<item name="android:background">@drawable/mydivider</item>
</style>
</resources>Create a file at res/drawable/mydivider.xml and add the following code
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#29A1C9" />
<corners android:radius="0.5dp" />
<stroke
android:color="#FFFFFF"
android:width="0.1dp" />
</shape>How to style the standard react-native android picker?
$ brew update
$ brew install watchman
Error: What went wrong: Could not determine the dependencies of task ':react-native-screens:generateDebugRFile ...
Moving google() repository at the top of the list in file build.gradle.
Change applicationId in android/app/build.gradle
Error: Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)
https://github.com/facebook/react-native/issues/26687
react-native 配置全局loading,弹框,以及toast组件
$ yarn cache clean
If not work:
If you are sure the module exists, try these steps:
1. Clear watchman watches: watchman watch-del-all
2. Delete node_modules: rm -rf node_modules and run yarn install
3. Reset Metro's cache: yarn start --reset-cache
4. Remove the cache: rm -rf /tmp/metro-*Error: Could not find tools.jar. Please check that /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home contains a valid JDK installation.
we I run $ cd android && ./gradlew assembleRelease
yarn run v1.13.0
$ cd android && ./gradlew assembleRelease
> Task :@react-native-community_async-storage:compileReleaseJavaWithJavac FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':@react-native-community_async-storage:compileReleaseJavaWithJavac'.
> Could not find tools.jar. Please check that /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home contains a valid JDK installation.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 7s
19 actionable tasks: 18 executed, 1 up-to-date*
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.not this $ export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home
I remove flavor setting.
2020 12 9 update:
In my case:
I used the command /usr/libexec/java_home -V | grep jdk Cristian Gomez provided to find two paths:
Matching Java Virtual Machines (2):
1.8.181.13 (x86_64) "Oracle Corporation" - "Java" /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home
1.8.0_111 (x86_64) "Oracle Corporation" - "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home
Changing the .zshrc did not solve the problem.
Finally I copied tools.jar in /Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home/lib/ to /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/lib/ and solved the problem.
I don't know if this approach will lead to any unknown problems.
- Could not find tools.jar. Please check that /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home contains a valid JDK installation
- MACBOOK(OSX)最升到11.0.1后android 打包报错 Could not find tools.jar. Please check that /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home contains a valid JDK installation.
java -version
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home/
react-native run-androidreact-native unlink react-native-vector-icons
cd ios
rm -rf build/
mport Icon from 'react-native-vector-icons/FontAwesome';
Icon.loadFont();If cannot find server: adb reverse tcp:8081 tcp:8081
Modify these files can avoid require cycle:
IN DIR rn-fetch-blob/polyfill
all thease 4 files: Blob.js, Fetch.js, FileReader.js, XMLHttpRequest.js
// import RNFetchBlob from '../index.js'
import {NativeModules} from 'react-native';
const RNFetchBlob = NativeModules.RNFetchBlobexport JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_111.jdk/Contents/Home
export PATH=$JAVA_HOME/bin:$PATH
I have just solved the same issue like this:
Tools -> SDK Manager
Verify that the SDK platform package for Android 10.0 (the one with API level 29, like you defined in your gradle file) is checked. If not, check it and apply changes. Accept the licence terms, install the package and then File -> Sync Project with Gradle Files (or open the project again)
Android Studio: No build variant found error
error: package com.reactnativecommunity.rnpermissions does not exist
import com.reactnativecommunity.rnpermissions.RNPermissionsPackage;Android Studio>File>Sync Project with Gradle Files
npm I jetifier
npx jetify
### Invariant Violation: "XXX" has not been registered. This can happen if:...
```sh
Invariant Violation: "XXX" has not been registered. This can happen if:
* Metro (the local dev server) is run from the wrong folder. Check if Metro is running, stop it and restart it in the current project.
* A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called.project/app.json:
{
"name": "XXX",
"displayName": "XXX"
}project/package.json:
{
"name": "XXX",
// ...
}如果将上述图片的 google() 和 jcenter() 各自改为
maven { url 'https://maven.aliyun.com/repository/google' }
maven { url 'https://maven.aliyun.com/repository/jcenter' }
即可以运行成功,记得多处更改。
另一种:将react native库里的build.gradle里的https://maven.google.com改为https://maven.aliyun.com/repository/public/。比如这次出问题的node_modules/@react-native-community/masked-view/android/build.gradle.
add "build:ios": "react-native bundle --entry-file='index.js' --bundle-output='./ios/main.jsbundle' --dev=false --platform='ios'" to package.json.
In Xcode, add main.jsbundle to Target → Build Phases → Copy Bundle Resources
react-native run-ios build failure "x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler " #1311
That's because there is a new version of Flipper and React Native might not come with the right one so best is to go in your podfile and add this use_flipper!({ 'Flipper' => '0.74.0' }) then run pod install
use_flipper!({ 'Flipper' => '0.87.0', 'Flipper-Folly' => '2.5.3', 'Flipper-RSocket' => '1.3.1' })
$ yarn add fbjs
Try This it worked for me
for android
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res/
**EDIT**
for ios
`react-native bundle --entry-file ./index.js --platform ios --bundle-output ios/main.jsbundle --assets-dest ios`
Thank you @kalpa
解决方式:
-
Edit Scheme -- Run -- Arguments -- Enviroment Variables
-
增加 Name: OS_ACTIVITY_MODE
Value: disable
重新调试就好了