初始化
注意,react-native-cli已被弃用!
最终初始化方法如下:
//安装yarn,替代npm
npm install -g yarn
//最新version为0.69,要求用java 11来编译android
//用java 8更方便,所以指定RN version为0.65
npx react-native init MyApp --version 0.65
按需微调
- 更改applicationId,位于android/app/build.gradle
- 更改app_name,位于android/app/src/main/res/values/strings.xml
- 更改AppTheme,位于android/app/src/main/res/values/styles.xml
<style name="AppTheme" parent="Theme.AppCompat.DayNight.NoActionBar">
<item name="android:statusBarColor">#000000</item>
</style>
如上指定statusBarColor,以便RN实现透明状态栏:
<StatusBar
translucent={true}
backgroundColor={'#0f00'}
barStyle={'dark-content'}
/>
- 可设android:windowSoftInputMode=“adjustNothing”,以免输入键盘压缩页面,位于android/app/src/main/AndroidManifest.xml
文本输入及处理
参考:
RN官网TextInput
React-Native TextInput 只支持输入数字
React-Native输入数字,每4个隔一个空格
RN的输入控件为TextInput,设其**keyboardType={‘numeric’}**以便弹出数字键盘。
而要仅限输入数字,还得要用正则处理:
const [phoneCode, phoneCode_] = useState('');
...
<TextInput
placeholder='输入验证码'
maxLength={phoneCodeLength}
keyboardType={'numeric'}
value={phoneCode}
onChangeText={(text) => {
//"\D"代表非数字
//"/g"代表全部处理
text = text.replace(/\D+/g, '');
//处理后的内容又填到输入框
phoneCode_(text);
}}
/>
通过绝对路径引用资源
参考:
下面(1)、(2)、(3)内容一样,(1)时间最早!
(1) babel-plugin-module-resolver 模块解析插件
(2) react-native 相对项目路径导入组件 ___ babel-plugin-module-resolver
(3) babel-plugin-module-resolver
(4) React Native中绝对路径配置 babel-plugin-module-resolver
(5) 理解 babel.config.js 和 babelrc
安装插件
yarn add babel-plugin-module-resolver --dev
修改babel.config.js,位于项目根目录:
module.exports = {
presets: ['module:metro-react-native-babel-preset'],
plugins: [
['module-resolver', {
root: ['.'],
alias: {
'src': './src',
'res': './res',
},
}],
],
};
然后便可化繁为简(需要重启metro,即yarn start)
<Image
source={require('res/login_bg.png')} //之前为'../../res/login_bg.png'
resizeMode='stretch'
style={{
width: '100%',
height: '100%',
position: 'absolute',
}}
/>
路由及导航
参考:
react-navigation
第二章 RN的第一个项目:导航+底部条切换+页面跳转
数据持久化
参考:
《React-Native系列》28、 RN之AsyncStorage
RN 的持久化存储(AsyncStorage)的使用
网络请求
参考:
axios官网
Timeout feature in the axios library is not working
axios设置timeout没用,补救方案:
let source = axios.CancelToken.source();
let timeout = config.timeout
setTimeout(() => {
source.cancel(`timeout of ${timeout}ms`);
}, timeout);
config.cancelToken = source.token;
axios.get(url, config);