React.js - 第2天
備注說明:該筆記來自于黑馬培訓(xùn)課筆記愚隧,因?yàn)橘|(zhì)量好,為方便學(xué)習(xí)和 查閱钞螟。
0. 安裝 React Developer Tools 調(diào)試工具
React Developer Tools - Chrome 擴(kuò)展下載安裝地址
主要內(nèi)容
1. React中創(chuàng)建組件
第1種 - 創(chuàng)建組件的方式
使用構(gòu)造函數(shù)來創(chuàng)建組件勤众,如果要接收外界傳遞的數(shù)據(jù)论寨,需要在 構(gòu)造函數(shù)的參數(shù)列表中使用
props
來接收赖临;必須要向外return一個(gè)合法的JSX創(chuàng)建的虛擬DOM胞锰;
function Hello () { // return null return <div>Hello 組件</div>}
// 使用組件并 為組件傳遞 props 數(shù)據(jù)<Hello name={dog.name} age={dog.age} gender={dog.gender}></Hello>// 在構(gòu)造函數(shù)中,使用 props 形參兢榨,接收外界 傳遞過來的數(shù)據(jù)function Hello(props) { // props.name = 'zs' console.log(props) // 結(jié)論:不論是 Vue 還是 React嗅榕,組件中的 props 永遠(yuǎn)都是只讀的;不能被重新賦值吵聪; return <div>這是 Hello 組件 --- {props.name} --- {props.age} --- {props.gender}</div>}
?.jsx
后綴名:// 打開 webpack.config.js ,并在導(dǎo)出的配置對(duì)象中吟逝,新增 如下節(jié)點(diǎn):resolve: { extensions: ['.js', '.jsx', '.json'], // 表示帽蝶,這幾個(gè)文件的后綴名,可以省略不寫 alias: { '@': path.join(__dirname, './src') } }
@
路徑符號(hào)第2種 - 創(chuàng)建組件的方式
使用 class 關(guān)鍵字來創(chuàng)建組件
ES6 中 class 關(guān)鍵字励稳,是實(shí)現(xiàn)面向?qū)ο缶幊痰男滦问剑?/p>
了解ES6中 class 關(guān)鍵字的使用
constructor
的基本使用extends
關(guān)鍵字實(shí)現(xiàn)繼承基于class關(guān)鍵字創(chuàng)建組件
// 如果要使用 class 定義組件,必須 讓自己的組件局蚀,繼承自 React.Componentclass 組件名稱 extends React.Component { // 在 組件內(nèi)部,必須有 render 函數(shù),作用:渲染當(dāng)前組件對(duì)應(yīng)的 虛擬DOM結(jié)構(gòu) render(){ // render 函數(shù)中恕稠,必須 返回合法的 JSX 虛擬DOM結(jié)構(gòu) return <div>這是 class 創(chuàng)建的組件</div> }}
2. 兩種創(chuàng)建組件方式的對(duì)比
注意:使用 class 關(guān)鍵字創(chuàng)建的組件琅绅,有自己的私有數(shù)據(jù)(this.state) 和 生命周期函數(shù);
注意:使用 function 創(chuàng)建的組件鹅巍,只有props千扶,沒有自己的私有數(shù)據(jù)和 生命周期函數(shù);
- 如果一個(gè)組件需要有自己的私有數(shù)據(jù),則推薦使用:class創(chuàng)建的有狀態(tài)組件敛苇;
- 如果一個(gè)組件不需要有私有的數(shù)據(jù)妆绞,則推薦使用:無狀態(tài)組件;
- React官方說:無狀態(tài)組件枫攀,由于沒有自己的state和生命周期函數(shù)括饶,所以運(yùn)行效率會(huì)比 有狀態(tài)組件稍微高一些;
有狀態(tài)組件和無狀態(tài)組件之間的本質(zhì)區(qū)別就是:有無state屬性来涨、和 有無生命周期函數(shù)图焰;
props
和 state/data
之間的區(qū)別- props 中的數(shù)據(jù)都是外界傳遞過來的;
- state/data 中的數(shù)據(jù)蹦掐,都是組件私有的技羔;(通過 Ajax 獲取回來的數(shù)據(jù)僵闯,一般都是私有數(shù)據(jù));
- props 中的數(shù)據(jù)都是只讀的藤滥;不能重新賦值鳖粟;
CommentList: [ { id: 1, user: '張三', content: '哈哈,沙發(fā)' }, { id: 2, user: '李四', content: '哈哈超陆,板凳' }, { id: 3, user: '王五', content: '哈哈牺弹,涼席' }, { id: 4, user: '趙六', content: '哈哈,磚頭' }, { id: 5, user: '田七', content: '哈哈时呀,樓下山炮' }]
4. 設(shè)置樣式
style
樣式<h1 style={ {color: 'red', fontWeight: 200} }></h1>
- 修改
webpack.config.js
這個(gè)配置文件张漂,為css-loader
添加參數(shù):{ test: /\.css$/, use: ['style-loader', 'css-loader?modules'] } // 為 .css 后綴名的樣式表 啟用 CSS 模塊化
- 在需要的組件中,
import
導(dǎo)入樣式表谨娜,并接收模塊化的 CSS 樣式對(duì)象:import cssObj from '../css/CmtList.css'
- 在需要的HTML標(biāo)簽上航攒,使用
className
指定模塊化的樣式:<h1 className={cssObj.title}>評(píng)論列表組件</h1>
localIdentName
自定義生成的類名格式,可選的參數(shù)有:- [path] 表示樣式表
相對(duì)于項(xiàng)目根目錄
所在路徑 - [name] 表示 樣式表文件名稱
- [local] 表示樣式的類名定義名稱
- [hash:length] 表示32位的hash值
- 例子:
{ test: /\.css$/, use: ['style-loader', 'css-loader?modules&localIdentName=[path][name]-[local]-[hash:5]'] }
:local()
和 :global()
-
:local()
包裹的類名趴梢,是被模塊化的類名漠畜,只能通過className={cssObj.類名}
來使用
同時(shí),:local
默認(rèn)可以不寫坞靶,這樣憔狞,默認(rèn)在樣式表中定義的類名,都是被模塊化的類名彰阴; -
:global()
包裹的類名瘾敢,是全局生效的,不會(huì)被css-modules
控制尿这,定義的類名是什么簇抵,就是使用定義的類名className="類名"
.title
這樣的類樣式選擇器,才會(huì)被模塊化控制射众,類似于body
這樣的標(biāo)簽選擇器碟摆,不會(huì)被模塊化控制;在項(xiàng)目中啟用模塊化并同時(shí)使用bootstrap
.scss
文件.css
結(jié)尾.scss
文件,啟用模塊化即可罗洗;cnpm i sass-loader node-sass -D
安裝能夠解析scss
文件的loader{ test: /\.scss$/, use: ['style-loader', 'css-loader?modules&localIdentName=[path][name]-[local]-[hash:5]', 'sass-loader'] } // 打包處理 scss 文件的 loader
?5. React 中綁定事件的注意點(diǎn)
onClick
、onMouseOver
onClick= { function }
<button onClick={ () => this.show('傳參') }>按鈕</button>// 事件的處理函數(shù)屑宠,需要定義為 一個(gè)箭頭函數(shù),然后賦值給 函數(shù)名稱show = (arg1) => { console.log('show方法' + arg1)}
this.setState({ })
6. 綁定文本框與state中的值(單向數(shù)據(jù)流)
v-model
指令,可以很方便的實(shí)現(xiàn) 數(shù)據(jù)的雙向綁定
卫玖;單向數(shù)據(jù)流
假瞬,也就是 只能把 state 上的數(shù)據(jù)綁定到 頁面陕靠,無法把 頁面中數(shù)據(jù)的變化,自動(dòng)同步回 state 脱茉; 如果需要把 頁面上數(shù)據(jù)的變化剪芥,保存到 state,則需要程序員手動(dòng)監(jiān)聽onChange
事件琴许,拿到最新的數(shù)據(jù)税肪,手動(dòng)調(diào)用this.setState({ })
更改回去;<input type="text" style={{ width: '100%' }} value={this.state.msg} onChange={() => this.textChanged()} ref="mytxt" /> // 響應(yīng) 文本框 內(nèi)容改變的處理函數(shù) textChanged = () => { // console.log(this); // console.log(this.refs.mytxt.value); this.setState({ msg: this.refs.mytxt.value }) }
?7. 使用ref獲取DOM元素引用
和 Vue 中差不多榜田,vue 為頁面上的元素提供了ref
的屬性益兄,如果想要獲取 元素引用,則需要使用this.$refs.引用名稱
在 React 中箭券,也有
ref
, 如果要獲取元素的引用this.refs.引用名稱
8. 組件的生命周期
-
組件創(chuàng)建階段:特點(diǎn):一輩子只執(zhí)行一次
componentWillMount:
render:
componentDidMount: -
組件運(yùn)行階段:按需屁魏,根據(jù) props 屬性 或 state 狀態(tài)的改變滔以,有選擇性的 執(zhí)行 0 到多次
componentWillReceiveProps:
shouldComponentUpdate:
componentWillUpdate:
render:
componentDidUpdate: -
組件銷毀階段:一輩子只執(zhí)行一次
defaultProps
- constructor()
- componentWillMount()
- render()
- componentDidMount()
- componentWillReceiveProps(nextProps)
- shouldComponentUpdate(nextProps, nextState)
- componentWillUpdate(nextProps, nextState)
- render()
- componentDidUpdate(prevProps, prevState)
- componentWillUnmount()
9. 通過Counter計(jì)數(shù)器的小案例 - 了解生命周期函數(shù)
props
屬性提供默認(rèn)值 和 進(jìn)行類型校驗(yàn),需要先運(yùn)行cnpm i prop-types --save
props
提供默認(rèn)值 // 為組件提供 默認(rèn)的 props 屬性值 static defaultProps = { initcount: 0 // 默認(rèn)值為0 如果用戶沒有傳遞 氓拼,則 默認(rèn)就是0你画; 如果用戶傳遞了,則 以用戶傳遞的為準(zhǔn) }
props
進(jìn)行類型校驗(yàn) // 3. 進(jìn)行 props 屬性的類型校驗(yàn), static propTypes = {} 是固定寫法 static propTypes = { initcount: PropTypes.number.isRequired // 規(guī)定 外界在傳遞 initcount 的時(shí)候桃漾,必須是 number 值類型坏匪,否則 ,會(huì)在終端報(bào)警告 // isRequired 表示 這個(gè) props 屬性值 是必須要傳遞的 }
?10. 使用React中的事件撬统,綁定count自增
11. 發(fā)表評(píng)論案例
相關(guān)文章
類型校驗(yàn)Animation Add-Ons
?