上手JSX

搭建小型react項目
mkdir reactdemo
cd reactdemo
npm init -y
npm install --save-dev webpack webpack-cli webpack-dev-server
npm install --save-dev html-webpack-plugin clean-webpack-plugin
npm install --save react react-dom
npm install --save-dev babel-loader @babel/core @babel/preset-react
npm install --save-dev style-loader css-loader
npm install --save-dev file-loa
echo const path = require('path'); >> webpack.config.js

//webpack.config.js
 const path = require('path');
 const HtmlWebapckPlugin = require("html-webpack-plugin");
 const {CleanWebpackPlugin} = require("clean-webpack-plugin");

 module.exports = {
     mode:'development',
     devtool:'cheap-source-map',
     devServer:{
         port:3000,
         contentBase:[path.join(__dirname),path.join(__dirname,'imgs')]
     },
     entry:"./src/index.js",
     output:{
         filename:"bundle.js",
         path:path.join(__dirname,"dist")
     },
     module:{
         rules:[
             {
                 test:/\.js$/,
                 include:/src/,
                 exclude:/node_modules/,
                 use:{
                     loader:'babel-loader',
                     options:{
                         presets:['@babel/preset-react']
                     }
                 }
             },
             {
                 test:/\.css$/,
                 include:/src/,
                 use:['style-loader','css-loader']
             },
             {
                 test:/\.gif$/,
                 use:'file-loader'
             }
         ]
     },
     plugins:[
         new HtmlWebapckPlugin({
             template:'./index.html'
         }),
         new CleanWebpackPlugin()
     ]
 }
//package.json
  "scripts": {
    "build": "webpack --config webpack.config.js",
    "start": "webpack-dev-server --config webpack.config.js"
  },
//index.html
<body>
    <div id="root"></div>
</body>
//index.css
.head{
    font-weight: normal;
}
//index.js
import React from "react";
import ReactDOM from "react-dom";
import './index.css';

const element = <h1 className='head'>hello world</h1>;
ReactDOM.render(
    element,
    document.querySelector('#root')
)

npm run start,瀏覽器地址欄輸入localhost:3000即可。

JSX中可以使用任意形式 javascript表達式,只需要用 {} 把它們括起來就行
  • 例1:{}裏放一個變量,{name}
//index.js
import React from "react";
import ReactDOM from "react-dom";
const name = "Tom";
const element = <h1>hello,{name}</h1>;
ReactDOM.render(
    element,
    document.getElementById('root')
)

可以把JSX拆成多行,用()括起來就行。

const element = (
    <h1>
        hello,{name}
    </h1>
);
  • 例2:{}裏放 函數調用返回的結果 ,{formatUser(user}
//index.js
import React from "react";
import ReactDOM from "react-dom";
function formatUser(user){
    const {firstName,lastName} = user;
    return `${firstName} ${lastName}`;
}
const user = {
    firstName:'John' ,
    lastName:'Wilson'
}

const element = (
    <h1>
        hello,{formatUser(user)}
    </h1>
);
ReactDOM.render(
    element,
    document.getElementById('root')
)

if語句中使用JSX
//index.js
import React from "react";
import ReactDOM from "react-dom";

function formatUser(user){
    const {firstName,lastName} = user;
    return `${firstName} ${lastName}`;
}
const user = {
    firstName:'John',
    lastName:'Wilson'
}
function getGreeting(user){
    if(user){
        return <h1>hello,{formatUser(user)}</h1>
    }else{
        return <h1>hello,stranger</h1>;
    }
}
ReactDOM.render(
    // getGreeting(),
    getGreeting(user),
    document.getElementById('root')
)
循環語句中使用JSX
//index.js
import React from "react";
import ReactDOM from "react-dom";

var books = [
    {
        title:"你今天真好看",
        author:'莉茲·克里莫'
    },
    {
        title:'我的不完美',
        author:'rene'
    }
];
const list = (
    <ul>
        {
            books.map((book,idx) => (
            <li key={idx}>{book.title},{book.author}</li>
            ))
        }
    </ul>
)
ReactDOM.render(
    list,
    document.getElementById('root')
)
JSX中的屬性

JSX中的屬性,要麼是字符串,如:id="h"className="head";要麼用{}括起來,如src={imgUrl}
如果標籤中沒有內容,可以直接用/>閉合標籤,像<img src={imgUrl}/>

//index.js
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";

const imgUrl = './doraemon.gif'
const element = (
    <div>
    <h1 id="h" className="head">hello</h1>
    <img src={imgUrl}/>
    </div>

)
ReactDOM.render(
    element,
    document.getElementById('root')
)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章