react组件的使用

2019-08-27  本文已影响0人  pawn_c

紧接上一篇文章jsx的使用

在src下创建components文件夹
创建并编辑Hello.jsx文件

import React from 'react'

function Hello(props){
    return <a>姓名:{props.name}---年龄:{props.age}</a>
}
export default Hello

在index.js下导入

import Hello from './components/Hello.jsx'

index.js最终文件如下


//这两个导入的时候,接收的成员名称,必须这么写
import React from 'react'//创建组件、虚拟dom元素,生命周期
import ReactDOM from 'react-dom'//把创建好的组件和虚拟dom放到页面上展示

import Hello from './components/Hello.jsx'

/*
<div><h1 id = "myh1" title="this is title">hello pawn</h1></div>
*/

/*
html是最优秀的标记语言:
在js文件中,默认不能写这种类似于html的标记,否则打包会失败
可以使用babel来转换这些标签
这种在js中混合html的语法,叫做jsx语法,符合xml规范的js
但是jsx的本质还是转换成React.createElement来执行的
*/


const mydiv = <h1>hello ß1pawn</h1>

/*
参数1:要渲染的那个虚拟dom元素
参数2:指定页面上一个容器
*/
const people = {
    name:"pawn",
    age:24
}
ReactDOM.render(<div><Hello {...people}></Hello></div>,document.getElementById('app'))

然后在webpack.config.js里添加识别jsx的配置

module: {
        rules: [
            {
                test: /\.jsx$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            }
        ]
    }

最终如下

const path = require('path');
const HtmlWebPackPlugin = require('html-webpack-plugin');//导入 在内存中自动生成index页面的插件

//创建一个插件的实例对象
const htmlPlugin = new HtmlWebPackPlugin({
   template:path.join(__dirname,'./src/index.html'),//源文件
   filename:'index.html'//生成的内存中的首页名称
})
module.exports = {
   mode:'development', //development开发。production 发布
   plugins:[
       htmlPlugin
   ],
   module: {
       rules: [
           {
               test: /\.js|jsx$/,
               exclude: /node_modules/,
               use: {
                   loader: "babel-loader"
               }
           }
       ]
   }

}

重新运行,成功

上一篇 下一篇

猜你喜欢

热点阅读