Day55 (React)

1.React导引 (JS框架)

(Lab_Hello > index.html)

(1)安装/引用 React 的 JavaScript
development.js 核心功能
react-dom.development.js UI处理;把虚拟的dom转为实体

    <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>    

(2)写入内容
(2-1)ReactDOM.render(在React核心建立一个元素,放到这)--->渲染/动态

    <div id="root"></div>    ReactDOM.render(    React.createElement("h1", null, "Hello, world!"),    document.getElementById("root"));

(2-2)使用翻译html MOD => babel.min.js

   <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>    <script type="text/babel">   //type="text/babel" 必要 babel.min.js才敢介入      ReactDOM.render(            <h1>Hello, world!</h1>,             document.getElementById("root")      );    </script>

(2-3)建立一个App元件,在React.Component里 并 使用babel.min.js翻译html

   <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>    <script type="text/babel">      class MyApp extends React.Component {        // 建立一个App元件,在React.Component里        render() {          return <h1>Hello world!</h1>;        }      }       // ReactDOM.render(元件,输出ID)      ReactDOM.render(<MyApp />, document.getElementById("root"));    </script>

2.物件製作浅规则------------------------------>重要

第一个字都要大写

(1)React - Calss版本

製作Clock元件(物件)继承React.Component
使用时须super()引用想使用的属性
state是内建的,无须引用

      //使用React.Component製作Clock元件(物件),props这个MOD的方法,新增this.state属性      class Clock extends React.Component {        constructor(props) {          // constructor: 製作预设值          super(props); //React.Component里面的props先抓出来给自己(Clock) ; 父亲                    // state建议不要改名          this.state = { date: new Date() }; //利用props增加一个属性state状态       }

(2)React - function版本

不须constructor:预设

      function Welcome(props) {        return (          <h1>            Hello, {props.FirstName}, {props.LastName}          </h1>        );      }      const element = (        <div>          <Welcome FirstName="Jeter" LastName="111" />          <Welcome FirstName="Messi" LastName="111" />          <Welcome FirstName="Jordan" LastName="111" />        </div>        // FirstName="Jeter" key : vaule      );      ReactDOM.render(element, document.getElementById("root"));

Js

      function Student(sname, sage) {        // Student = {x:y}        this.StudentName = sname; //this S = x        this.StudentAge = sage; //this S = y        this.cat = function () {          console.log("喵");          console.log(this.StudentName); //物件里面的属性 this        };      }

3.React的元件製作MOD - Simple React Snippets

(Lab_Hello_Toolchain > Lab > hello)

Simple React Snippets 协助产生元件的MOD

(1)安装 create-react-app 全域安装

 > npm install create-react-app -g

(2)切换到习惯的工作目录,启动「命名提示字元」,建立react资料夹
C:\XXX\react_part_1\Lab_Hello_Toolchain\Lab

 > create-react-app hello

Happy hacking!>{}<(会安装很久。)

会建立一个新的资料夹: C:\XXX\react_part_1\Lab_Hello_Toolchain\Lab\hello

(3)C:\XXX\react_part_1\Lab_Hello_Toolchain\Lab\hello下执行

      package.json  "scripts": {        "start": "react-scripts start",      },

npm start

会出现
http://img2.58codes.com/2024/20137684gZyO8HJWZ3.png
或手动执行http://localhost:3000/

(4)观察专案

(4-1)public > index.html

主画面

(4-2)src > App.js

App.js = App元件<App />

所以改变内容网页也会改变

(4-3)src > index.js

把网页镶嵌近来

    ReactDOM.render(      <React.StrictMode>        <App />      </React.StrictMode>,      document.getElementById('root')    );

(5)将 src 资料夹的全部档案都删除

(6)src内新增index.js

   import React from 'react';   import ReactDOM from 'react-dom';   const element = <h1>Hello World</h1>;   ReactDOM.render(element, document.getElementById("root"));

npm start

Hello World出现~~~~~

(7) Ctrl + C 结束 Development Server.

(8)安装与使用 Bootstrap

npm install bootstrap@4.1.1

(9)src内更改index.js
display-1为BS样式

    import React from 'react';    import ReactDOM from 'react-dom';    import "bootstrap/dist/css/bootstrap.css";    // h1 class="display-1"一样可执行,className特意区分Class,让工程师比较好辨识    const element = <h1 className="display-1">Hello World</h1>;    ReactDOM.render(element, document.getElementById("root"));

npm start

(10) Ctrl + C 结束 Development Server.

以下解释「放到MAMP亦可执行」---->失败?需提问:问不出来,自己找XD

(11) 编译与布署 React 应用程式

npm run build

新增资料夹build
C:\XXX\react_part_1\Lab_Hello_Toolchain\Lab\hello\build

(12)将 build 资料夹複製到 c:\MAMP\htdocs

c:\MAMP\htdocs\build
build改名hello
c:\MAMP\htdocs\hello

(13)C:\MAMP\conf\apache\httpd.conf
将下列内容,附加到档案结尾处

    LISTEN 8001    <VirtualHost *:8001>        DocumentRoot "C:\MAMP\htdocs\hello"    </VirtualHost>

http://localhost:8001/

(14)练习结束

还原 C:\MAMP\conf\apache\httpd.conf 档案内容删除 hello 资料夹

因此,想要使用React放到apache可执行时
先用build打包,后放到c:\MAMP\htdocs内(似PHP)
更改httpd.conf port号的路径,即可使用


4.class有分美术样式(CSS)或是后端类别

美术样式(CSS .class):
className特意区分Class,让工程师比较好辨识

    const element = <h1 className="display-1">Hello World</h1>;    ReactDOM.render(element, document.getElementById("root"));

后端类别(class):
React

      class MyApp extends React.Component {        //  创一个 名为MyApp的类别 继承自 React.Component        //  并使用React.Component 里的render() 方法        //  命名:开头大写        render() {          return <h1>Hello world!</h1>;        }      }

5.React - JSX :好维护的 HTML 架构

(Lab_JSX > index_0.html)

(1)先试试看之前呼叫的用法
Lab_JSX > index_0.html
计算 + 网页 + 资料

(2)在 JSX 呼叫函式

      const dataItem = {        scientificName: "Everes lacturnus rileyi",        commonName: "南方燕蓝灰蝶",      };      function formatName(species) {           // 1.JSX版           return (           <span>           {species.commonName} <br /> {species.scientificName}           </span>           );                   // 2.字串版           // 字串版  ,<br>无效 无法换行           // return `${species.commonName} <br /> ${species.scientificName}`;           }           // 3.JSX版 + 判别式           var x = 100;           if (x >= 100) {           return ( //return不行去掉;(),会变成 return;(Js的特性,会帮忙加;)            <span>              {species.commonName} <br /> {species.scientificName}            </span>           );             } else {          return <div> 值未达100时 </div>;             }          }              const element = <h3> {formatName(dataItem)} </h3>;
若不想使用const element = <h3> {formatName(dataItem)} </h3>;把字串改成元件      const element = (        <div>          {dataItem.commonName} <br /> {dataItem.scientificName}        </div>      );

(3)新增照片

      const element = (        <div className="col-4">          <h3> {formatName(dataItem)} </h3>          <img src="images/rileyi.jpg" />        </div>        // <img src={dataItem.image}  />      ,  需加  "/"        // <img src= {dataItem.image} ></img> , 或需加</img>      );

6.空白的换行,js特性(帮忙加;)会製造bug

      function formatName(species) {         return (  //正确           <span>             {" "}             {species.commonName} <br /> {species.scientificName}{" "}           </span>         );

此处return不行去掉;(),会变成 return; (Js的特性,会帮忙加; 这个程式就不会往下跑了(return))

      function formatName(species) {         return //错误            <span>             {" "}             {species.commonName} <br /> {species.scientificName}{" "}           </span>      }

7.React - render

(Lab_Render > index_0.html)

      function displayTime() {        const element = (          <div>            <h1>Hello, world!</h1>            <h2>It is {new Date().toString()}.</h2>          </div>        );        ReactDOM.render(element, document.getElementById("root"));      }      setInterval(displayTime, 1000);

非ajax,只是一般的setInterval


8.render()

通常将虚拟转成实体的关键字,如ejs
10.ajax
可以去捞后端资料,随时更新


9.React - Props 製作物件资料们

(Lab_Render > index_0.html)
想法:Props是一种MOD,她有偷偷动手脚让我可以直接呼叫物件

(1)Welcome元件製作:

       class Welcome extends React.Component {          render() {            return (              <h1>                Hello, {this.props.FirstName} , {this.props.LastName}              </h1> // props取自React.Component的属性及值            ); //大小写注意          }        }

或是这样写也对

      function Welcome(props) {        return (          <h1>            Hello, {props.FirstName}, {props.LastName}          </h1>        );      }

(2)在Welcome元件放入资料 FirstName="Jeter" key : vaule

      const element = (        <div>          <Welcome FirstName="Jeter" />          <Welcome FirstName="Messi" />          <Welcome FirstName="Jordan" />        </div>      );      ReactDOM.render(element, document.getElementById("root"));

10.state + props + setState 製作随时更新的内容

(Lab_Render > Lab_State_LifeCycle)
注意:只能输出给id

1.ReactDOM.render要输出的时候,会先根据製作物件

    ReactDOM.render(<Clock />, document.getElementById("root")); 

2.製作Clock元件(物件),props这个MOD的方法,新增this.state属性

       class Clock extends React.Component {        constructor(props) {          super(props);          //state不要改名          this.state = { date: new Date() }; //利用props增加一个属性state       }

製作元件方式,有两种Class及function方式製作

(2-1)Class : constructor:预设

      class Car {        constructor(changecolor, changewheels) {          // this.color 原本设定的          // var myCar = new Car("green");          this.color = changecolor; //颜色          this.wheels = changewheels; //轮子        }        showInfo() {          console.log(this.color);          console.log(this.wheels);        }      }      var myCar = new Car("green", 4);      myCar.showInfo();

Class可以继承extends React.Component而取得使用内建的属性
使用时须super()引用

      // constructor: 建立 ; 当建立 类别物件时 会自动产生constructor里面的内容      class Clock extends React.Component {        constructor(props) {          super(props); //React.Component里面的props先抓出来给自己 ; 父亲          //state建议不要改名          this.state = { date: new Date() }; //利用props增加一个属性state状态        }

(2-2)function

不须constructor:预设

      function Welcome(props) {        return (          <h1>            Hello, {props.FirstName}, {props.LastName}          </h1>        );      }      const element = (        <div>          <Welcome FirstName="Jeter" LastName="111" />          <Welcome FirstName="Messi" LastName="111" />          <Welcome FirstName="Jordan" LastName="111" />        </div>        // FirstName="Jeter" key : vaule      );      ReactDOM.render(element, document.getElementById("root"));

3.元件的render()方法呼叫

        render() {            return (            <div>              <h1>Hello, world!</h1>              <h2>It is {this.state.date.toLocaleTimeString()}.</h2>            </div>          );        }

4.网页内容放进document.getElementById("root"))

    ReactDOM.render(<Clock />, document.getElementById("root")); 

5.当元件 放到id=root后 react 会自动去找有无componentDidMount() 方法

     componentDidMount() {          this.timerId = setInterval(() => {            // 开始计时            // 写法1:            // this.state.date = new Date();  // 单纯只有属性给Date() 网页不会刷新            // this.setState(this.state.date);             // 当「 状态或资料要改变 」时,需使用.setState() 方法让他去呼叫render()「 重新产生画面 」            // 写法2:            // this.setState({ date: new Date() }); //把上面 两行写成一行            // 写法3:            this.state.date = new Date(); //单纯只有属性给Date() 网页不会刷新            this.setState({}); //使用空物件,react 也会自动去侦测要改变的属性          }, 1000);        }

6.当网页或元件 即将卸载或网页关掉后 react 会自动去找有无 componentWillUnmount()方法

        componentWillUnmount() {          clearInterval(this.timerId); // 停止记时        }

setState() 执行顺序

  class Clock extends React.Component {        constructor(props) {          super(props);           // 1. <Clock/>继承父层的state属性,用来搭配setState()方法用          this.state = { date: new Date() };        }          componentDidMount() {          this.timerId = setInterval(() => {                // 2. 单纯只有属性给Date() 网页不会刷新            this.state.date = new Date();                         this.setState({ date: new Date() }); // 3. 抓改变而刷新                        // 4. 方法名称 和 同名的属性名称{ date: new Date() } 做对应            // this.setState({});使用空物件,react 也会自动去侦测要改变的属性                      }, 1000);        }              render() {          return (            <div>              <h1>Hello, world!</h1>              //5. 字串输出              <h2>It is {this.state.date.toLocaleTimeString()}.</h2>             </div>          );        }             //6. 网页内容放进document.getElementById("root"))     ReactDOM.render(<Clock />, document.getElementById("root"));

11. Q:setInterval 那边,请问一定要箭头函式的写法吗?

是,如果用function,this会搞丢

            componentDidMount() {                this.timerId = setInterval( () => {                    this.setState({ date: new Date() });                }, 1000);            }

12.State(状态) vs props(属性)

State(状态) => 内建
props(属性) => 跟父亲继承

      class Clock extends React.Component {        constructor(props) {          // constructor: 製作预设值          super(props); //React.Component里面的props先抓出来给自己(Clock) ; 父亲          // state建议不要改名          this.state = { date: new Date() }; //利用props增加一个属性state状态        }

13.render id的方式

   <script type="text/babel">      function Myapp() {        return (          <div>            <ul>              <li>1</li>              <li>2</li>              <li>3</li>            </ul>            <ol>hi</ol>          </div>        );      }      ReactDOM.render(<Myapp />, document.getElementById("root"));  //方法1.      ReactDOM.render(<Myapp />, root);  //方法2.

14.解释

套件:小工具包
框架:套件的进阶版,可用来完成一个专案
api:别人写好的方法
api文件:使用说明书


class是类别、function()是方法
class是透过继承 React.Component => 把class类别变成元件了
元件 是 框架的专有名词
元件 想成 标籤元素
而 function() 则是 透过 React 自身 把它变成元件了
变成 我们一般 html的那种标籤

       class Clock extends React.Component {        constructor(props) {          super(props);          //state不要改名          this.state = { date: new Date() }; //利用props增加一个属性state       }

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章