React組件的用法概述
組件的定義:
- 理解:用來實現局部功能效果的代碼和資源的集合(html/css/js/image等等)
- 為什么要用組件: 一個界面的功能更復雜
- 作用:復用編碼, 簡化項目編碼, 提高運行效率
React內的組件分為容器組件和展示組件。
React組件
函數式組件
<div id="test"></div> <script type="text/babel"> //1.創(chuàng)建函數式組件(必須大寫,函數必須有返回值) function MyComponent(){ console.log(this); //此處的this是undefined,因為babel編譯后開啟了嚴格模式 return <h2>我是用函數定義的組件(適用于【簡單組件】的定義)</h2> } //2.渲染組件到頁面 ReactDOM.render(<MyComponent/>,document.getElementById('test')) /* 執(zhí)行了ReactDOM.render(<MyComponent/>.......之后,發(fā)生了什么? 1.React解析組件標簽,找到了MyComponent組件。 2.發(fā)現組件是使用函數定義的,隨后調用該函數,將返回的虛擬DOM轉為真實DOM,隨后呈現在頁面中。 */ </script>
類式組件
<div id="test"></div> <script type="text/babel"> //1.創(chuàng)建類式組件 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')) /* 執(zhí)行了ReactDOM.render(<MyComponent/>.......之后,發(fā)生了什么? 1.React解析組件標簽,找到了MyComponent組件。 2.發(fā)現組件是使用類定義的,隨后new出來該類的實例,并通過該實例調用到原型上的render方法。 3.將render返回的虛擬DOM轉為真實DOM,隨后呈現在頁面中。 */ </script>
組件實例三大屬性
state
state是組件對象最重要的屬性, 值是對象(可以包含多個key-value的組合);組件被稱為"狀態(tài)機", 通過更新組件的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) 箭頭函數 - 狀態(tài)數據,不能直接修改或更新
<div id="test"></div> <script type="text/babel"> //1.創(chuàng)建類式組件 class Weather extends React.Component { constructor(props){ super(props) //初始化狀態(tài) this.state = {isHot:false} } //render調用幾次? ———— 1+n次 1是初始化的那次 n是狀態(tài)更新的次數 render(){ //讀取狀態(tài) 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.創(chuàng)建組件 class Weather extends React.Component{ //構造器調用幾次? ———— 1次 constructor(props){ console.log('constructor'); super(props) //初始化狀態(tài) this.state = {isHot:false,wind:'微風'} //解決changeWeather中this指向問題 this.changeWeather = this.changeWeather.bind(this) } //render調用幾次? ———— 1+n次 1是初始化的那次 n是狀態(tài)更新的次數 render(){ console.log('render'); //讀取狀態(tài) 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 //嚴重注意:狀態(tài)必須通過setState進行更新,且更新是一種合并,不是替換。 this.setState({isHot:!isHot}) console.log("asf",this); //嚴重注意:狀態(tài)(state)不可直接更改,下面這行就是直接更改!??! //this.state.isHot = !isHot //這是錯誤的寫法 } } //2.渲染組件到頁面 ReactDOM.render(<Weather/>,document.getElementById('test')) </script>
實際常用的簡寫形式:
<div id="test"></div> <script type="text/babel"> //1.創(chuàng)建組件 class Weather extends React.Component{ //初始化狀態(tài) 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"> //創(chuàng)建組件 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>
實際常用的簡寫形式:
//創(chuàng)建組件 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"> //創(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為數值 } //指定默認標簽屬性值 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創(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// 解構賦值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"> //創(chuàng)建組件 class Demo extends React.Component{ showData = ()=>{ console.log(this.input1.value) } showData2 = ()=>{ const {input2} = this console.log(input2.value) } render(){ return(// 回調函數:定義后沒有馬上調用,最終卻又執(zhí)行了。 <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是當前所處的節(jié)點<input type="text" placeholder="點擊按鈕提示數據"/>。 // 箭頭函數沒有自己的this,往外找render的this是組件實例對象 } } //渲染組件到頁面 ReactDOM.render(<Demo a="1" b="2"/>,document.getElementById('test')) </script>
createRef創(chuàng)建ref容器:
React.createRef調用后可以返回一個容器,該容器可以存儲被ref所標識的節(jié)點,該容器是“專人專用”的
<div id="test"></div> <script type="text/babel"> //創(chuàng)建組件 class Demo extends React.Component{ myRef = React.createRef()// 用幾個創(chuàng)建幾個 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>
到此這篇關于React組件的用法和理解的文章就介紹到這了,更多相關React組件的用法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
React從react-router路由上做登陸驗證控制的方法
本篇文章主要介紹了React從react-router路由上做登陸驗證控制的方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05React?中如何將CSS?visibility?屬性設置為?hidden
這篇文章主要介紹了React中如何將CSS?visibility屬性設置為?hidden,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-05-05