近日學習react17.0.2版本的筆記,不多講了上教程加代碼
- 新建專案
- 關于React
- React JSX
- React面向組件編程
- 注意點
- 組件三大核心屬性1: state
- 組件三大核心屬性2: props
- 組件三大核心屬性3: refs與事件處理
- 明天繼續更新
新建專案
- npm install -g create-react-app 全域安裝
- create-react-app my-app 新建并對react專案進行命名(注:專案名稱不能有大寫)
- cd my-app
- num run start
PS:以上是webpack創建react專案方式 本人也只用過webpack其他方式暫時先不做,
關于React
英文官網: https://reactjs.org/
中文官網: https://react.docschina.org/
其優點
1.宣告式編碼
2.組件化編碼
3.React Native 撰寫原生應用
4.高效(優秀的Diffing演算法)
還是不講廢話了 直接來開始react的使用
React JSX
學習react的時候這個是必看的
-
JSX全稱: JavaScript XML
-
react定義的一種類似于XML的JS擴展語法: JS + XML本質是
React.createElement方法的語法糖
-
作用: 用來簡化創建虛擬DOM
-
寫法:var ele =
Hello JSX!
注意1:它不是字串, 也不是HTML/XML標簽
注意2:它最終產生的就是一個JS物件
-
標簽名任意: HTML標簽或其它標簽
-
標簽屬性任意: HTML標簽屬性或其它
-
基本語法規則
遇到 <開頭的代碼, 以標簽的語法決議: html同名標簽轉換為html同名元素, 其它標簽需要特別決議
遇到以 { 開頭的代碼,以JS語法決議: 標簽中的js運算式必須用{ }包含 -
babel.js的作用
瀏覽器不能直接決議JSX代碼, 需要babel轉譯為純JS的代碼才能運行
只要用了JSX,都要加上type=“text/babel”, 宣告需要babel來處理
React面向組件編程
注意點
-
組件名必須首字母大寫
-
虛擬DOM元素只能有一個根元素
-
虛擬DOM元素必須有結束標簽
組件三大核心屬性1: state
import React,{Component} from "react";
export default class StateTest extends Component{
constructor(props){
super(props)
this.state={
my:'5555'
}
}
render(){
const abc = this.state //state的
console.log(abc); //{'my:5555'}
return(
<div>我是state組件</div>
)
}
}
來看一下輸出結果

對于state的理解
state是組件物件最重要的屬性, 值是物件(可以包含多個key-value的組合)
組件被稱為"狀態機", 通過更新組件的state來更新對應的頁面顯示(重新渲染組件)
注意:組件中render方法中的this為組件實體物件
組件自定義的方法中this為undefined,如何解決?
- 強制系結this: 通過函式物件的bind()
- 箭頭函式
狀態資料,不能直接修改或更新
組件三大核心屬性2: props
import React,{Component} from "react";
export default class Props extends Component{
constructor(props){
super(props)
console.log(props)
}
render(){
return(
<div>
真的挺牛逼的
</div>
)
}
}
組件三大核心屬性3: refs與事件處理
- 字串形式的ref
<input ref="input1"/>
- 回呼形式的ref
<input ref={(c)=>{this.input1 = c}}
- createRef創建ref容器
import React, { Component } from "react";
export default class InputRef extends Component {
constructor(props) {
super(props)
this.inputdiv = React.createRef()
}
getvalue() {
console.log(this.inputdiv.current.value) //能獲取input中的值
}
render() {
return (
<form>
<input type='text' ref={this.inputdiv}></input>
<button onClick={() => this.getvalue()}>獲取</button>
</form>
)
}
}
-
事件處理
- 通過onXxx屬性指定事件處理函式(注意大小寫)
- React使用的是自定義(合成)事件, 而不是使用的原生DOM事件
- React中的事件是通過事件委托方式處理的(委托給組件最外層的元素)
- 通過event.target得到發生事件的DOM元素物件
import React, { Component } from "react";
export default class Ref extends Component{
constructor(props){
super(props)
this.mydiv = React.createRef()
this.inputidv = React.createRef()
}
componentDidMount(){
console.log(this.mydiv.current)
}
render(){
return(
<div ref={this.mydiv}>
995
</div>
)
}
}
this.my.current能獲取Dom

明天繼續更新
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/374789.html
標籤:其他
