RN

作者: 苹果雪梨渣 | 来源:发表于2020-10-22 11:25 被阅读0次
核心库 :react-native-web
npm install --save react-native-web   (当前集成的是0.14.3)
安装babel及相关 preset / plugin
npm install --save-dev @babel/core  (当前集成的7.12.3)
npm install --save-dev @babel/runtime  (当前集成的7.12.1)
npm install --save-dev @babel/preset-env  (当前集成的7.12.1)
npm install --save-dev @babel/preset-react  (当前集成的7.12.1)
npm install --save-dev @babel/preset-flow    (当前集成的7.12.1)
安装WebPack 与 WebPackSever 和及相关Loader
npm install --save-dev webpack   (当前集成的4.31.0)
npm install --save-dev webpack-cli  (当前集成的3.3.2)
npm install --save-dev webpack-dev-server   (当前集成的3.3.1)
npm install --save-dev babel-loader  (当前集成的8.1.0)
npm install --save-dev react-dom (当前集成的17.0.0)
npm install --save-dev babel-plugin-transform-class-properties (当前集成的6.24.1)

项目根目录下找到 babel.config.js文件
module.exports = {
  presets: [
    'module:metro-react-native-babel-preset',
    [
      "@babel/preset-env", {
      "modules": "commonjs"
    }
    ],
    "@babel/preset-react",
    "@babel/preset-flow"
  ],

  plugins: [
    [
      "transform-class-properties"
    ]
  ]
  
};
项目根目录 创建文件夹 index.html
<!DOCTYPE html>
<html lang="en" style="height:100%">
<head>
    <meta charset="UTF-8">
    <title>React Native Web In Superbuy App</title>
    <meta name="viewport" content="initial-scale=1.0,width=device-width">
    <style>
        html, body { height: 100%; width: 100%; overflow: hidden; }
        .react-app { height: 100%; overflow: hidden; }
    </style>
</head>
<body style="height:100%">
<div id="react-app" style="display:flex;height:100%">
</div>
<script src="./build/RN.web.js"></script>
</body>
</html>
项目根目录 找到 index.js
import {AppRegistry,Platform} from 'react-native';
import App from './App';
import {name as appName} from './app.json';

AppRegistry.registerComponent(appName, () => App);
if(Platform.OS === 'web' ){
    AppRegistry.runApplication(appName, {
        initialProps: {},
        rootTag: document.getElementById('react-app')
    });
}
项目根目录 找到 APP.js 注释里面所有文件
import React, {
    Component
} from 'react';
import {
    StyleSheet,
    View,
    Text,
    FlatList,
    InteractionManager,
    Image,
} from 'react-native';

export default class App extends Component {
    
    constructor(props) {
        super(props)

        this.state = {
            dataSource: [],
        };
    }

    componentDidMount() {
        console.ignoredYellowBox = [
            'Warning: componentWillUpdate has been renamed',
            'Warning: componentWillMount has been renamed',
            'Warning: componentWillReceiveProps has been renamed',
            'Warning: codePush.SyncStatus'
            // 'Warning: isMounted(...) is deprecated',
        ]
        console.disableYellowBox = true

        let newArray = []
        for (let i = 0; i < 10; i++) {
            let dict = {title:"标题",image:'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1603344640367&di=1831eb733035d39e970b0a22110e3b1b&imgtype=0&src=http%3A%2F%2Fa0.att.hudong.com%2F70%2F91%2F01300000261284122542917592865.jpg'}
            newArray.push(dict)
        }

        InteractionManager.runAfterInteractions(() => {
            //执行耗时的同步任务
            this.setState({dataSource: newArray});
        });

    }


    render() {
        return (
            <View style={{flex:1}}>
            <FlatList
                keyExtractor={(item, index) => item.key = index.toString()}
                ListHeaderComponent={this.renderHeader}
                renderItem={this.renderItem}
                ref={(flatList)=>this.flatList = flatList}
                data={this.state.dataSource}
                ItemSeparatorComponent={()=> {
                    return <View style={{height:10,width:'100%',backgroundColor:'lightgray'}}/>
                }}
            />
            </View>
        );
    }


    renderHeader =()=>{
        return (
            <View style={{paddingTop:44,height:100,backgroundColor:'red',justifyContent:'center',alignItems:'center'}}>
                <Text>头部</Text>
            </View>
        )
    }


    renderItem =(item)=> {
      let rowData = item.item;
        let Index = rowData.key;
        return (  <View style={{
            backgroundColor: 'white',
            height: 100,
            justifyContent: 'space-between',
            paddingHorizontal: 10,
            flexDirection: 'row',
            alignItems:'center'
        }}>
            <Text>{rowData.title} {Index}</Text>
                <Image style={{height:70,width:70}} source={{uri:rowData.image}}/>
        </View>
        )
    }
};



const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
});


项目根目录 创建文件夹 webpack.config.js
const path = require('path');

module.exports = {
  entry: './index.js',
  output: {
    filename: 'RN.web.js',
    path: path.resolve(__dirname, 'build'),
  },
  mode: 'development',
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        use: {
          loader: 'babel-loader',
          // options: {
          //    presets: ['@babel/preset-env']
          // }
        }
      }
    ]
  },

  resolve: {
    alias: {
      'react-native$': 'react-native-web'
    }
  },

  devServer: {
    contentBase: path.join(__dirname, ""), //本地服务器所加载的页面所在的目录
    historyApiFallback: true,//不跳转
    host:'0.0.0.0',
    port:7000,
    inline: true,//实时刷新
    hot:true,//Enable webpack's Hot Module Replacement feature
    compress:true,//Enable gzip compression for everything served
    overlay: true, //Shows a full-screen overlay in the browser
    stats: "errors-only" ,//To show only errors in your bundle
    open:true, //When open is enabled, the dev server will open the browser.
    proxy: {
      "/api": {
        target: "http://localhost:3000",
        pathRewrite: {"^/api" : ""}
      }
    }
  }
}

项目根目录 找到 package.json
  • 增加打包命令(开发)
  • 增加打包命令(生产)
  • 增加打开服务器命令
scripts": {
    "dev": "webpack --mode development",
    "build": "webpack --mode production",
    "server": "webpack-dev-server"
  },
当前项目根目录 打开终端输入 一下指令
npm run dev
npm run server
WeChat5aa5314f7942908d0e2309d9c033707d.png

相关文章

网友评论

      本文标题:RN

      本文链接:https://www.haomeiwen.com/subject/sfkumktx.html