網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
組件的定義:
- 理解:用來(lái)實(shí)現(xiàn)局部功能效果的代碼和資源的集合(html/css/js/image等等)
- 為什么要用組件:?一個(gè)界面的功能更復(fù)雜
- 作用:復(fù)用編碼,?簡(jiǎn)化項(xiàng)目編碼,?提高運(yùn)行效率
React內(nèi)的組件分為容器組件和展示組件。
React組件
函數(shù)式組件
<div id="test"></div> <script type="text/babel"> //1.創(chuàng)建函數(shù)式組件(必須大寫(xiě),函數(shù)必須有返回值) function MyComponent(){ console.log(this); //此處的this是undefined,因?yàn)閎abel編譯后開(kāi)啟了嚴(yán)格模式 return <h2>我是用函數(shù)定義的組件(適用于【簡(jiǎn)單組件】的定義)</h2> } //2.渲染組件到頁(yè)面 ReactDOM.render(<MyComponent/>,document.getElementById('test')) /* 執(zhí)行了ReactDOM.render(<MyComponent/>.......之后,發(fā)生了什么? 1.React解析組件標(biāo)簽,找到了MyComponent組件。 2.發(fā)現(xiàn)組件是使用函數(shù)定義的,隨后調(diào)用該函數(shù),將返回的虛擬DOM轉(zhuǎn)為真實(shí)DOM,隨后呈現(xiàn)在頁(yè)面中。 */ </script>
類(lèi)式組件
<div id="test"></div> <script type="text/babel"> //1.創(chuàng)建類(lèi)式組件 class MyComponent extends React.Component { render(){ //render是放在哪里的?—— MyComponent的原型對(duì)象上,供實(shí)例使用。 //render中的this是誰(shuí)?—— MyComponent的實(shí)例對(duì)象 <=> MyComponent組件實(shí)例對(duì)象。 console.log('render中的this:',this); return <h2>我是用類(lèi)定義的組件(適用于【復(fù)雜組件】的定義)</h2> } } //2.渲染組件到頁(yè)面 ReactDOM.render(<MyComponent/>,document.getElementById('test')) /* 執(zhí)行了ReactDOM.render(<MyComponent/>.......之后,發(fā)生了什么? 1.React解析組件標(biāo)簽,找到了MyComponent組件。 2.發(fā)現(xiàn)組件是使用類(lèi)定義的,隨后new出來(lái)該類(lèi)的實(shí)例,并通過(guò)該實(shí)例調(diào)用到原型上的render方法。 3.將render返回的虛擬DOM轉(zhuǎn)為真實(shí)DOM,隨后呈現(xiàn)在頁(yè)面中。 */ </script>
組件實(shí)例三大屬性
state
state是組件對(duì)象最重要的屬性, 值是對(duì)象(可以包含多個(gè)key-value的組合);組件被稱(chēng)為"狀態(tài)機(jī)", 通過(guò)更新組件的state來(lái)更新對(duì)應(yīng)的頁(yè)面顯示(重新渲染組件)。
class Person extends React.Component{ state = {isHot:false,wind:'weifeng'} render(){ const {isHot, wind} = this.state return ( <h1>今天天氣很{isHot ? '炎熱' : '涼爽'},{wind}</h1> ) } }
- 組件中render方法中的this為組件實(shí)例對(duì)象
- 組件自定義的方法中this為undefined,如何解決?
a) 強(qiáng)制綁定this: 通過(guò)函數(shù)對(duì)象的bind()
b) 箭頭函數(shù) - 狀態(tài)數(shù)據(jù),不能直接修改或更新
<div id="test"></div> <script type="text/babel"> //1.創(chuàng)建類(lèi)式組件 class Weather extends React.Component { constructor(props){ super(props) //初始化狀態(tài) this.state = {isHot:false} } //render調(diào)用幾次? ———— 1+n次 1是初始化的那次 n是狀態(tài)更新的次數(shù) render(){ //讀取狀態(tài) const {isHot} = this.state//解構(gòu)賦值,不這樣的話(huà)也可以this.state.isHot?'炎熱' : '涼爽' return <h1>今天天氣比較{isHot?'炎熱' : '涼爽'}</h1> } //2.渲染組件到頁(yè)面 ReactDOM.render(<Weather/>,document.getElementById('test')) </script>
<div id="test"></div> <script type="text/babel"> //1.創(chuàng)建組件 class Weather extends React.Component{ //構(gòu)造器調(diào)用幾次? ———— 1次 constructor(props){ console.log('constructor'); super(props) //初始化狀態(tài) this.state = {isHot:false,wind:'微風(fēng)'} //解決changeWeather中this指向問(wèn)題 this.changeWeather = this.changeWeather.bind(this) } //render調(diào)用幾次? ———— 1+n次 1是初始化的那次 n是狀態(tài)更新的次數(shù) render(){ console.log('render'); //讀取狀態(tài) const {isHot,wind} = this.state//解構(gòu)賦值 return <h1 onClick={this.changeWeather}>今天天氣很{isHot ? '炎熱' : '涼爽'},{wind}</h1> } //changeWeather調(diào)用幾次? ———— 點(diǎn)幾次調(diào)幾次 changeWeather(){ //changeWeather放在哪里? ———— Weather的原型對(duì)象上,供實(shí)例使用 //由于changeWeather是作為onClick的回調(diào),所以不是通過(guò)實(shí)例調(diào)用的,是直接調(diào)用 //類(lèi)中的方法默認(rèn)開(kāi)啟了局部的嚴(yán)格模式,所以changeWeather中的this為undefined console.log('changeWeather'); //獲取原來(lái)的isHot值 const isHot = this.state.isHot //嚴(yán)重注意:狀態(tài)必須通過(guò)setState進(jìn)行更新,且更新是一種合并,不是替換。 this.setState({isHot:!isHot}) console.log("asf",this); //嚴(yán)重注意:狀態(tài)(state)不可直接更改,下面這行就是直接更改?。?! //this.state.isHot = !isHot //這是錯(cuò)誤的寫(xiě)法 } } //2.渲染組件到頁(yè)面 ReactDOM.render(<Weather/>,document.getElementById('test')) </script>
實(shí)際常用的簡(jiǎn)寫(xiě)形式:
<div id="test"></div> <script type="text/babel"> //1.創(chuàng)建組件 class Weather extends React.Component{ //初始化狀態(tài) state = {isHot:false,wind:'微風(fēng)'} render(){ const {isHot,wind} = this.state return <h1 onClick={this.changeWeather}>今天天氣很{isHot ? '炎熱' : '涼爽'},{wind}</h1> } //自定義方法————要用賦值語(yǔ)句的形式+箭頭函數(shù) changeWeather = ()=>{ const isHot = this.state.isHot this.setState({isHot:!isHot}) } } //2.渲染組件到頁(yè)面 ReactDOM.render(<Weather/>,document.getElementById('test')) </script>
props
每個(gè)組件對(duì)象都會(huì)有props(properties的簡(jiǎn)寫(xiě))屬性;組件標(biāo)簽的所有屬性都保存在props中。ReactDOM.render(<Person name='jerry' age={19} sex='男'/>,document.getElementById('test1'))
通過(guò)標(biāo)簽屬性從組件外向組件內(nèi)傳遞變化的數(shù)據(jù);注意: 組件內(nèi)部不要修改props數(shù)據(jù)(只讀的)。
<div id="test1"></div> <div id="test2"></div> <div id="test3"></div> <!-- 除了之前的三個(gè)外還需引入prop-types,用于對(duì)組件標(biāo)簽屬性進(jìn)行限制 --> <script type="text/javascript" src="../js/prop-types.js"></script> <script type="text/babel"> //創(chuàng)建組件 class Person extends React.Component{ render(){ const {name,age,sex} = this.props// 不然下面就要用this.props.name //props是只讀的,this.props.name = 'jack'會(huì)報(bào)錯(cuò) return ( <ul> <li>姓名:{name}</li> <li>性別:{sex}</li> <li>年齡:{age+1}</li> </ul> ) } } //對(duì)標(biāo)簽屬性進(jìn)行類(lèi)型、必要性的限制 Person.propTypes = {// 注意這個(gè)和下一行的大小寫(xiě) name:PropTypes.string.isRequired, //限制name必傳,且為字符串 sex:PropTypes.string,//限制sex為字符串 age:PropTypes.number,//限制age為數(shù)值 speak:PropTypes.func,//限制speak為函數(shù) } //指定默認(rèn)標(biāo)簽屬性值 Person.defaultProps = { sex:'男',//sex默認(rèn)值為男 age:18 //age默認(rèn)值為18 } //渲染組件到頁(yè)面 ReactDOM.render(<Person name="jerry" age={19} sex="男"/>,document.getElementById('test1'))//{19}js ReactDOM.render(<Person name="tom" speak={speak} sex="女"/>,document.getElementById('test2')) // 批量傳遞props(標(biāo)簽屬性) const p = {name:'老劉',age:18,sex:'女'} // ReactDOM.render(<Person name={p.name} age={p.age} sex={p.sex}/>,document.getElementById('test3')) ReactDOM.render(<Person {...p}/>,document.getElementById('test3'))// 上面的簡(jiǎn)寫(xiě) function speak(){ console.log('我說(shuō)話(huà)了'); } </script>
實(shí)際常用的簡(jiǎn)寫(xiě)形式:
//創(chuàng)建組件 class Person extends React.Component{ constructor(props){// 一般都省略 //構(gòu)造器是否接收props,是否傳遞給super,取決于:是否希望在構(gòu)造器中通過(guò)this訪(fǎng)問(wèn)props;想要父類(lèi)中的方法與屬性就要傳,也要接。 // console.log(props); super(props) console.log('constructor',this.props); } //對(duì)標(biāo)簽屬性進(jìn)行類(lèi)型、必要性的限制 static propTypes = {// 前面加static以把屬性寫(xiě)在類(lèi)內(nèi)部 name:PropTypes.string.isRequired, //限制name必傳,且為字符串 sex:PropTypes.string,//限制sex為字符串 age:PropTypes.number,//限制age為數(shù)值 } //指定默認(rèn)標(biāo)簽屬性值 static defaultProps = { sex:'男',//sex默認(rèn)值為男 age:18 //age默認(rèn)值為18 } render(){ // console.log(this); const {name,age,sex} = this.props //props是只讀的,this.props.name = 'jack'會(huì)報(bào)錯(cuò) return ( <ul> <li>姓名:{name}</li> <li>性別:{sex}</li> <li>年齡:{age+1}</li> </ul> ) } }
函數(shù)式組件使用props:
<div id="test1"></div> <script type="text/babel"> //創(chuàng)建組件 function Person (props){ const {name,age,sex} = props return ( <ul> <li>姓名:{name}</li> <li>性別:{sex}</li> <li>年齡:{age}</li> </ul> ) } Person.propTypes = { name:PropTypes.string.isRequired, //限制name必傳,且為字符串 sex:PropTypes.string,//限制sex為字符串 age:PropTypes.number,//限制age為數(shù)值 } //指定默認(rèn)標(biāo)簽屬性值 Person.defaultProps = { sex:'男',//sex默認(rèn)值為男 age:18 //age默認(rèn)值為18 } //渲染組件到頁(yè)面 ReactDOM.render(<Person name="jerry"/>,document.getElementById('test1')) </script>
refs與事件處理
組件內(nèi)的標(biāo)簽可以定義ref屬性來(lái)標(biāo)識(shí)自己。
1.字符串形式的ref <input ref="input1"/>
(效率不高,不推薦)
2.回調(diào)函數(shù)形式的ref <input ref={(c)=>{this.input1 = c}}
3.createRef創(chuàng)建ref容器 <input ref={this.myRef}/>
字符串形式的ref:
<div id="test"></div> <script type="text/babel"> //創(chuàng)建組件 class Demo extends React.Component{ showData = ()=>{// 用refs取代document.getElementById const {input1} = this.refs// 解構(gòu)賦值this.refs.input1 console.log(input1)// <input type="text" placeholder="點(diǎn)擊按鈕提示數(shù)據(jù)"> console.log(input1.value) } showData2 = ()=>{ const {input2} = this.refs console.log(input2.value) } render(){ return( <div> <input ref="input1" type="text" placeholder="點(diǎn)擊按鈕提示數(shù)據(jù)"/> <button onClick={this.showData}>點(diǎn)我提示左側(cè)的數(shù)據(jù)</button> <input ref="input2" onBlur={this.showData2} type="text" placeholder="失去焦點(diǎn)提示數(shù)據(jù)"/> </div> ) } } //渲染組件到頁(yè)面 ReactDOM.render(<Demo a="1" b="2"/>,document.getElementById('test')) </script>
回調(diào)函數(shù)形式的ref:
<div id="test"></div> <script type="text/babel"> //創(chuàng)建組件 class Demo extends React.Component{ showData = ()=>{ console.log(this.input1.value) } showData2 = ()=>{ const {input2} = this console.log(input2.value) } render(){ return(// 回調(diào)函數(shù):定義后沒(méi)有馬上調(diào)用,最終卻又執(zhí)行了。 <div> <input ref={c => this.input1 = c } type="text" placeholder="點(diǎn)擊按鈕提示數(shù)據(jù)"/> <button onClick={this.showData}>點(diǎn)我提示左側(cè)的數(shù)據(jù)</button> <input onBlur={this.showData2} ref={c => this.input2 = c } type="text" placeholder="失去焦點(diǎn)提示數(shù)據(jù)"/> </div> )// 打印c是當(dāng)前所處的節(jié)點(diǎn)<input type="text" placeholder="點(diǎn)擊按鈕提示數(shù)據(jù)"/>。 // 箭頭函數(shù)沒(méi)有自己的this,往外找render的this是組件實(shí)例對(duì)象 } } //渲染組件到頁(yè)面 ReactDOM.render(<Demo a="1" b="2"/>,document.getElementById('test')) </script>
createRef創(chuàng)建ref容器:
React.createRef調(diào)用后可以返回一個(gè)容器,該容器可以存儲(chǔ)被ref所標(biāo)識(shí)的節(jié)點(diǎn),該容器是“專(zhuān)人專(zhuān)用”的
<div id="test"></div> <script type="text/babel"> //創(chuàng)建組件 class Demo extends React.Component{ myRef = React.createRef()// 用幾個(gè)創(chuàng)建幾個(gè) myRef2 = React.createRef() showData = ()=>{ alert(this.myRef.current.value); } showData2 = ()=>{ alert(this.myRef2.current.value); } showData3 = (event)=>{// 不要過(guò)度使用ref,有時(shí)直接用js事件源對(duì)象也行 alert(event.target.value); } render(){ return( <div> <input ref={this.myRef} type="text" placeholder="點(diǎn)擊按鈕提示數(shù)據(jù)"/> <button onClick={this.showData}>點(diǎn)我提示左側(cè)的數(shù)據(jù)</button> <input onBlur={this.showData2} ref={this.myRef2} type="text" placeholder="失去焦點(diǎn)提示數(shù)據(jù)"/> <input onBlur={this.showData3} type="text" placeholder="失去焦點(diǎn)提示數(shù)據(jù)"/> </div> ) } } //渲染組件到頁(yè)面 ReactDOM.render(<Demo a="1" b="2"/>,document.getElementById('test')) </script>
原文鏈接:https://blog.csdn.net/zag666/article/details/129000727
相關(guān)推薦
- 2022-06-12 一文搞懂C語(yǔ)言static關(guān)鍵字的三個(gè)作用_C 語(yǔ)言
- 2022-03-24 Android繪制平移動(dòng)畫(huà)的示例代碼_Android
- 2022-05-06 python畫(huà)圖時(shí)給圖中的點(diǎn)加標(biāo)簽和plt.text的使用_python
- 2023-03-16 redis刪除hash的實(shí)現(xiàn)方式_Redis
- 2023-01-01 Android?webView加載數(shù)據(jù)時(shí)內(nèi)存溢出問(wèn)題及解決_Android
- 2022-08-10 Github簡(jiǎn)單易用的?Android?ViewModel?Retrofit框架_Android
- 2022-04-30 C語(yǔ)言程序環(huán)境中的預(yù)處理詳解_C 語(yǔ)言
- 2022-10-16 python?IO多路復(fù)用之epoll詳解_python
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門(mén)
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支