網站首頁 編程語言 正文
組件的定義:
- 理解:用來實現局部功能效果的代碼和資源的集合(html/css/js/image等等)
- 為什么要用組件:?一個界面的功能更復雜
- 作用:復用編碼,?簡化項目編碼,?提高運行效率
React內的組件分為容器組件和展示組件。
React組件
函數式組件
<div id="test"></div> <script type="text/babel"> //1.創建函數式組件(必須大寫,函數必須有返回值) function MyComponent(){ console.log(this); //此處的this是undefined,因為babel編譯后開啟了嚴格模式 return <h2>我是用函數定義的組件(適用于【簡單組件】的定義)</h2> } //2.渲染組件到頁面 ReactDOM.render(<MyComponent/>,document.getElementById('test')) /* 執行了ReactDOM.render(<MyComponent/>.......之后,發生了什么? 1.React解析組件標簽,找到了MyComponent組件。 2.發現組件是使用函數定義的,隨后調用該函數,將返回的虛擬DOM轉為真實DOM,隨后呈現在頁面中。 */ </script>
類式組件
<div id="test"></div> <script type="text/babel"> //1.創建類式組件 class MyComponent extends React.Component { render(){ //render是放在哪里的?—— MyComponent的原型對象上,供實例使用。 //render中的this是誰?—— MyComponent的實例對象 <=> MyComponent組件實例對象。 console.log('render中的this:',this); return <h2>我是用類定義的組件(適用于【復雜組件】的定義)</h2> } } //2.渲染組件到頁面 ReactDOM.render(<MyComponent/>,document.getElementById('test')) /* 執行了ReactDOM.render(<MyComponent/>.......之后,發生了什么? 1.React解析組件標簽,找到了MyComponent組件。 2.發現組件是使用類定義的,隨后new出來該類的實例,并通過該實例調用到原型上的render方法。 3.將render返回的虛擬DOM轉為真實DOM,隨后呈現在頁面中。 */ </script>
組件實例三大屬性
state
state是組件對象最重要的屬性, 值是對象(可以包含多個key-value的組合);組件被稱為"狀態機", 通過更新組件的state來更新對應的頁面顯示(重新渲染組件)。
class Person extends React.Component{ state = {isHot:false,wind:'weifeng'} render(){ const {isHot, wind} = this.state return ( <h1>今天天氣很{isHot ? '炎熱' : '涼爽'},{wind}</h1> ) } }
- 組件中render方法中的this為組件實例對象
- 組件自定義的方法中this為undefined,如何解決?
a) 強制綁定this: 通過函數對象的bind()
b) 箭頭函數 - 狀態數據,不能直接修改或更新
<div id="test"></div> <script type="text/babel"> //1.創建類式組件 class Weather extends React.Component { constructor(props){ super(props) //初始化狀態 this.state = {isHot:false} } //render調用幾次? ———— 1+n次 1是初始化的那次 n是狀態更新的次數 render(){ //讀取狀態 const {isHot} = this.state//解構賦值,不這樣的話也可以this.state.isHot?'炎熱' : '涼爽' return <h1>今天天氣比較{isHot?'炎熱' : '涼爽'}</h1> } //2.渲染組件到頁面 ReactDOM.render(<Weather/>,document.getElementById('test')) </script>
<div id="test"></div> <script type="text/babel"> //1.創建組件 class Weather extends React.Component{ //構造器調用幾次? ———— 1次 constructor(props){ console.log('constructor'); super(props) //初始化狀態 this.state = {isHot:false,wind:'微風'} //解決changeWeather中this指向問題 this.changeWeather = this.changeWeather.bind(this) } //render調用幾次? ———— 1+n次 1是初始化的那次 n是狀態更新的次數 render(){ console.log('render'); //讀取狀態 const {isHot,wind} = this.state//解構賦值 return <h1 onClick={this.changeWeather}>今天天氣很{isHot ? '炎熱' : '涼爽'},{wind}</h1> } //changeWeather調用幾次? ———— 點幾次調幾次 changeWeather(){ //changeWeather放在哪里? ———— Weather的原型對象上,供實例使用 //由于changeWeather是作為onClick的回調,所以不是通過實例調用的,是直接調用 //類中的方法默認開啟了局部的嚴格模式,所以changeWeather中的this為undefined console.log('changeWeather'); //獲取原來的isHot值 const isHot = this.state.isHot //嚴重注意:狀態必須通過setState進行更新,且更新是一種合并,不是替換。 this.setState({isHot:!isHot}) console.log("asf",this); //嚴重注意:狀態(state)不可直接更改,下面這行就是直接更改!!! //this.state.isHot = !isHot //這是錯誤的寫法 } } //2.渲染組件到頁面 ReactDOM.render(<Weather/>,document.getElementById('test')) </script>
實際常用的簡寫形式:
<div id="test"></div> <script type="text/babel"> //1.創建組件 class Weather extends React.Component{ //初始化狀態 state = {isHot:false,wind:'微風'} render(){ const {isHot,wind} = this.state return <h1 onClick={this.changeWeather}>今天天氣很{isHot ? '炎熱' : '涼爽'},{wind}</h1> } //自定義方法————要用賦值語句的形式+箭頭函數 changeWeather = ()=>{ const isHot = this.state.isHot this.setState({isHot:!isHot}) } } //2.渲染組件到頁面 ReactDOM.render(<Weather/>,document.getElementById('test')) </script>
props
每個組件對象都會有props(properties的簡寫)屬性;組件標簽的所有屬性都保存在props中。ReactDOM.render(<Person name='jerry' age={19} sex='男'/>,document.getElementById('test1'))
通過標簽屬性從組件外向組件內傳遞變化的數據;注意: 組件內部不要修改props數據(只讀的)。
<div id="test1"></div> <div id="test2"></div> <div id="test3"></div> <!-- 除了之前的三個外還需引入prop-types,用于對組件標簽屬性進行限制 --> <script type="text/javascript" src="../js/prop-types.js"></script> <script type="text/babel"> //創建組件 class Person extends React.Component{ render(){ const {name,age,sex} = this.props// 不然下面就要用this.props.name //props是只讀的,this.props.name = 'jack'會報錯 return ( <ul> <li>姓名:{name}</li> <li>性別:{sex}</li> <li>年齡:{age+1}</li> </ul> ) } } //對標簽屬性進行類型、必要性的限制 Person.propTypes = {// 注意這個和下一行的大小寫 name:PropTypes.string.isRequired, //限制name必傳,且為字符串 sex:PropTypes.string,//限制sex為字符串 age:PropTypes.number,//限制age為數值 speak:PropTypes.func,//限制speak為函數 } //指定默認標簽屬性值 Person.defaultProps = { sex:'男',//sex默認值為男 age:18 //age默認值為18 } //渲染組件到頁面 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(標簽屬性) 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'))// 上面的簡寫 function speak(){ console.log('我說話了'); } </script>
實際常用的簡寫形式:
//創建組件 class Person extends React.Component{ constructor(props){// 一般都省略 //構造器是否接收props,是否傳遞給super,取決于:是否希望在構造器中通過this訪問props;想要父類中的方法與屬性就要傳,也要接。 // console.log(props); super(props) console.log('constructor',this.props); } //對標簽屬性進行類型、必要性的限制 static propTypes = {// 前面加static以把屬性寫在類內部 name:PropTypes.string.isRequired, //限制name必傳,且為字符串 sex:PropTypes.string,//限制sex為字符串 age:PropTypes.number,//限制age為數值 } //指定默認標簽屬性值 static defaultProps = { sex:'男',//sex默認值為男 age:18 //age默認值為18 } render(){ // console.log(this); const {name,age,sex} = this.props //props是只讀的,this.props.name = 'jack'會報錯 return ( <ul> <li>姓名:{name}</li> <li>性別:{sex}</li> <li>年齡:{age+1}</li> </ul> ) } }
函數式組件使用props:
<div id="test1"></div> <script type="text/babel"> //創建組件 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為數值 } //指定默認標簽屬性值 Person.defaultProps = { sex:'男',//sex默認值為男 age:18 //age默認值為18 } //渲染組件到頁面 ReactDOM.render(<Person name="jerry"/>,document.getElementById('test1')) </script>
refs與事件處理
組件內的標簽可以定義ref屬性來標識自己。
1.字符串形式的ref <input ref="input1"/>
(效率不高,不推薦)
2.回調函數形式的ref <input ref={(c)=>{this.input1 = c}}
3.createRef創建ref容器 <input ref={this.myRef}/>
字符串形式的ref:
<div id="test"></div> <script type="text/babel"> //創建組件 class Demo extends React.Component{ showData = ()=>{// 用refs取代document.getElementById const {input1} = this.refs// 解構賦值this.refs.input1 console.log(input1)// <input type="text" placeholder="點擊按鈕提示數據"> console.log(input1.value) } showData2 = ()=>{ const {input2} = this.refs console.log(input2.value) } render(){ return( <div> <input ref="input1" type="text" placeholder="點擊按鈕提示數據"/> <button onClick={this.showData}>點我提示左側的數據</button> <input ref="input2" onBlur={this.showData2} type="text" placeholder="失去焦點提示數據"/> </div> ) } } //渲染組件到頁面 ReactDOM.render(<Demo a="1" b="2"/>,document.getElementById('test')) </script>
回調函數形式的ref:
<div id="test"></div> <script type="text/babel"> //創建組件 class Demo extends React.Component{ showData = ()=>{ console.log(this.input1.value) } showData2 = ()=>{ const {input2} = this console.log(input2.value) } render(){ return(// 回調函數:定義后沒有馬上調用,最終卻又執行了。 <div> <input ref={c => this.input1 = c } type="text" placeholder="點擊按鈕提示數據"/> <button onClick={this.showData}>點我提示左側的數據</button> <input onBlur={this.showData2} ref={c => this.input2 = c } type="text" placeholder="失去焦點提示數據"/> </div> )// 打印c是當前所處的節點<input type="text" placeholder="點擊按鈕提示數據"/>。 // 箭頭函數沒有自己的this,往外找render的this是組件實例對象 } } //渲染組件到頁面 ReactDOM.render(<Demo a="1" b="2"/>,document.getElementById('test')) </script>
createRef創建ref容器:
React.createRef調用后可以返回一個容器,該容器可以存儲被ref所標識的節點,該容器是“專人專用”的
<div id="test"></div> <script type="text/babel"> //創建組件 class Demo extends React.Component{ myRef = React.createRef()// 用幾個創建幾個 myRef2 = React.createRef() showData = ()=>{ alert(this.myRef.current.value); } showData2 = ()=>{ alert(this.myRef2.current.value); } showData3 = (event)=>{// 不要過度使用ref,有時直接用js事件源對象也行 alert(event.target.value); } render(){ return( <div> <input ref={this.myRef} type="text" placeholder="點擊按鈕提示數據"/> <button onClick={this.showData}>點我提示左側的數據</button> <input onBlur={this.showData2} ref={this.myRef2} type="text" placeholder="失去焦點提示數據"/> <input onBlur={this.showData3} type="text" placeholder="失去焦點提示數據"/> </div> ) } } //渲染組件到頁面 ReactDOM.render(<Demo a="1" b="2"/>,document.getElementById('test')) </script>
原文鏈接:https://blog.csdn.net/zag666/article/details/129000727
相關推薦
- 2022-06-17 Ruby序列化和持久化存儲(Marshal、Pstore)操作方法詳解_Golang
- 2022-06-07 nlp自然語言處理基于SVD的降維優化學習_python
- 2022-02-14 記關于Android開發中使用System.currentTimeMillis()不準確的問題
- 2022-07-20 NDArray?與?numpy.ndarray?互相轉換方式_python
- 2022-10-15 Go?Excelize?API源碼解讀GetSheetViewOptions與SetPageLayo
- 2022-04-09 Android項目中gradle的執行流程_Android
- 2022-07-17 Go語言入門exec的基本使用示例_Golang
- 2022-04-28 SQL?Server索引結構的具體使用_MsSql
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支