React組件的使用詳細講解
1.組件的創(chuàng)建方式
函數式組件
特別注意這里的寫法,如果要在 JSX 里寫 js 表達式(只能是表達式,不能是流程 控制語句),就需要加 {},包括注釋也是一樣,并且可以多層嵌套
// 函數式組件
// 寫組件模板的時候必須遵循jsx語法
function App() {
return (
<div className="App">
hello reactjs
</div>
);
}class組件
ES6 的加入讓 JavaScript 直接支持使用 class 來定義一個類,react 的第二種創(chuàng)建組件 的方式就是使用的類的繼承,ES6 class 是目前官方推薦的使用方式,它使用了 ES6 標準 語法來構建
// class組件
// 注意:組件名必須首字母大寫(為了和普通標識符區(qū)分開),必須繼承自 React.Component 組件
// class的好處就是可以在render并列的位置
// class組件中,使用的this是當前組件實例
// App這個組件必須繼承自React.Component
class App extends React.Component {
// App這個組件要想渲染什么由內部的render方法決定,必須要有render方法,這個render方法負責渲染組件的模板就是有什么標簽
// js中如果return后面沒有語句就會自動加分號
// 當想要使用插件時得改變 組件文件名的后綴改為jsx
// 定義組件狀態(tài)state,組件數據
// 在constructor函數中對組件狀態(tài)進行初始化
constructor(props) {
super(props)
this.state = {//初始化組件狀態(tài)
count: 100,
arr: ['nodejs', 'react', 'vue.js']
}
}
// state = 100
// state = {
// count: 100,
// arr: ['nodejs', 'react', 'vue.js']
// }
render() {//render中必須return返回 組件模板
return (
<div className="App">
<h1>{this.state.count}</h1>
<h1>{this.state.arr}</h1>
</div>
);
}
}2.組件命名規(guī)范
組件名稱必須以大寫字母開頭。
<Welcome name="james">
小駝峰命名來定義屬性
<Welcome className="blue" tabIndex="1" >
3.組件傳值props
函數組件通過參數 props 接收外部組件傳入的數據, 在組件內根據 props 處理 UI
傳遞值:
<Header id="1001" url="http://xxx.com"></Header>
接收值(函數式組件)
函數式組件用參數 props 接收值
function Header ( props ){
return (
<div className="header">
{/* 組件模板中使用 組件的屬性 */}
<h1>{props.id},{props.url}</h1>
</div>
)
}
類組件中處理props
類組件通過this.props接收外部組件傳入的數據,在組件內根據this.props處理UI
接收值(class組件)
class 組件內部用 this.props 接收值
class Header extends React.Component{
render(){
return (
<div className="header">
{/* 組件模板中使用 組件的屬性 */}
<h1>{this.props.id},{this.props.url}</h1>
</div>
)
}
}子組件:
import React, { Component } from 'react';
class Child extends Component {
handleClick() {
// this.props.title = 'state'; //props是只讀的.
}
render() {
return (
<div className="child">
{this.props.title}{this.props.count}
<button onClick={() => { this.handleClick() }}>更改</button>
</div>
);
}
}
export default Child;父組件中
<Child title="今天學習props" count={100} />
注意:
<></> 原名是<Fragment>可以省略,充當的是一個包裹元素(包裹其他標簽), 最終在頁面中不會渲染.
4.組件樣式sass
在react組件中,使用sass編寫組件樣式,需要依賴sass插件。
使用步驟:
下載插件
npm i sass -D
創(chuàng)建.scss文件,編寫sass代碼
在組件中引入scss文件
import './App.scss';
5.組件的生命周期函數
主文件
import './App.css';
import Child from './Child';
//react中存在兩種形式的組件: 函數式組件, 類組件
//使用 rcc 快速創(chuàng)建 類組件 ( 主要使用這個 )
//使用 rsf 快速創(chuàng)建 函數式組件
import React, { Component } from 'react';
class App extends Component {
// 掛載期(掛載期的方法會自動執(zhí)行,而且只執(zhí)行一次)
constructor(props) {//這個函數會在組件掛載前就執(zhí)行,組件并沒有顯示在頁面上
super(props);
console.log('constructor');
this.state = {}//初始化組件狀態(tài)
}
componentWillMount() {//掛載前
console.log('componentWillMount 將要掛載');
}
componentDidMount() {//掛載完成,組件就會顯示在頁面上
console.log('componentDidMount 掛載完成');
// 在這里發(fā)送網絡請求,創(chuàng)建定時器,事件監(jiān)聽,理由是:這個方法只執(zhí)行一次,而且會自動執(zhí)行
// 這里的this指的是組件實例this.timerid就是將定時器保存在當前組件實例身上,就可以在各個組件生命周期共享
// 還可以直接保存在組件狀態(tài)中,只不過保存在組件狀態(tài)中定時器是可以改變的,如果不變化就可以保存在組件實例身上
this.timerid = setInterval(() => {
console.log('定時器在執(zhí)行');
}, 1000)
}
// 更新期(更新期的方法可能會反復調用執(zhí)行)
// 性能優(yōu)化時寫的地方
shouldComponentUpdate(nextProps, nextState) {//控制組件是否更新,目的是提示組件性能(性能優(yōu)化)
// 組件性能優(yōu)化:把有效的更新進行更新,無效的更新就不讓它進行更新
// 組件狀態(tài)是否有變化,如果有變化就更新,沒有變化就不更新
// 當setState中的數據和state中的數據相等沒有必要更新
// if (this.state == nextState) {
// 滿足條件就不更新,傳進來的state是兩個對象,當每次更新的時候對象所指的地址都是不一樣的,所以不能直接比較,要將對象轉換為字符串進行比較
if (JSON.stringify(this.state) == JSON.stringify(nextState)) {
return false;
} else {
return true;//返回false 表示放棄更新,返回true 表示繼續(xù)更新
}
}
componentWillReceiveProps(nextProps) {//Props更新,才會執(zhí)行(可以用這個函數來監(jiān)聽Props的變化)
// nextProps 是最新的數據的對象
// 用這個函數監(jiān)聽父組件傳來的數據是否有變化
console.log('componentWillReceiveProps 將要更新');
}
componentWillUpdate() {
console.log('componentWillUpdate 將要更新');
}
componentDidUpdate() {
console.log('componentDidUpdate 更新完成');
}
// 卸載期
componentWillUnmount() {
console.log('componentWillUnmount 將要卸載');
// 在這里釋放所占用的資源(網路請求,定時器,事件監(jiān)聽)
clearInterval(this.timerid);
}
// render方法在組件初次渲染時會執(zhí)行一次,在之后的組件每次更新時都會執(zhí)行一次
render() { //渲染組件模板到視圖
return (
<div>
<h1 className="class" id="big" onClick={() => { this.handleClick() }}>hello reactjs</h1>
{/* 父組件先更新更新的時候子組件變化子組件更新子組件更新完父組件才更新完成 */}
<Child title={this.state.count} />
</div>
);
}
handleClick() {//組件狀態(tài)
this.setState({ count1 });
}
}
export default App;子文件
import React, { Component } from 'react';
class Child extends Component {
// 掛載期(掛載期的方法會自動執(zhí)行,而且只執(zhí)行一次)
constructor(props) {//這個函數會在組件掛載前就執(zhí)行,組件并沒有顯示在頁面上
super(props);
console.log('constructor');
this.state = {}//初始化組件狀態(tài)
}
componentWillReceiveProps(nextProps) {//Props更新,才會執(zhí)行(可以用這個函數來監(jiān)聽Props的變化)
// nextProps 是最新的數據的對象
// 用這個函數監(jiān)聽父組件傳來的數據是否有變化
// 傳過來的值是新的就會執(zhí)行,傳過來的值不是新的就不會執(zhí)行
// 這里傳過來的數據是一個對象,要將對象轉換為字符串進行比較,因為對象每次更新地址都會變化,只是值不變
console.log('Child componentWillReceiveProps 將要更新');
}
componentWillUpdate() {
console.log('Child componentWillUpdate 將要更新');
}
componentDidUpdate() {
console.log('Child componentDidUpdate 更新完成');
}
render() {
return (
<div>
</div>
);
}
}
export default Child;6.受控組件—表單處理
特別說明:HTML中表單元素是可輸入的,也就是有自己的可變狀態(tài),但是默認表單元素的值不受所在組件state的控制,也就是表單元素所在組件無法實時獲取最新的表單元素值
非受控組件
表單元素值不受所在組件狀態(tài)的控制,我們將這樣的表單元素稱為:非受控組件
受控組件
受控組件:值受到React組件狀態(tài)控制的表單元素
一般是通過defaultValue屬性,onChange事件配合將非受控組件變?yōu)槭芸亟M件
- 文本框、富文本框、下拉框操作value屬性
- 復選框操作checked屬性
import './App.css';
//react中存在兩種形式的組件: 函數式組件, 類組件
//使用 rcc 快速創(chuàng)建 類組件 ( 主要使用這個 )
//使用 rsf 快速創(chuàng)建 函數式組件
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
phone: '',
isRead: false//是否勾選協(xié)議
}
}
handleChange(e) {
this.setState({
phone: e.target.value
}, () => {
console.log(this.state);
})
}
handleChecked(e) {
this.setState({
isRead: e.target.checked
}, () => {
console.log(this.state);
})
}
render() { //渲染組件模板到視圖
return (
<div>
{/* 非受控元素變成受控元素,通過value和onChange綁定實現 */}
{/* value綁定,將組件狀態(tài)綁定到元素的value屬性 */}
{/* onChange綁定,當元素的值發(fā)生改變時更新元素的值到組件狀態(tài) */}
<input type="text" value={this.state.phone} onChange={(e) => { this.handleChange(e) }} placeholder='請輸入手機號' />
<input type="checkbox" value={this.state.isRead} onChange={(e) => { this.handleChecked(e) }} />
</div>
);
}
}
export default App;多表單元素操作
- 給表單元素添加name屬性,名稱與state相同
- 根據表單元素類型獲取對應值
- 在change事件處理程序中通過[name]來修改對應的state
import './App.css';
//react中存在兩種形式的組件: 函數式組件, 類組件
//使用 rcc 快速創(chuàng)建 類組件 ( 主要使用這個 )
//使用 rsf 快速創(chuàng)建 函數式組件
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
phone: '',
pass: '',
isRead: false//是否勾選協(xié)議
}
}
handleChange(e) {
// 獲取目標控件input元素對應的別名
// e.target.name
this.setState({
// 因為別名是個變量,所以用方括號括起來
// 如果是單選。復選框,通過e.target.checked取值
// 如果是其它元素,通過e.target.value取值
[e.target.name]: ((e.target.type == 'checkbox' || e.target.type == 'radio') ? e.target.checked : e.target.value)
}, () => {
console.log(this.state);
})
}
login() {
// 發(fā)送登錄請求
// 刪除里面沒有用的或者取出有用的傳過去
// 這樣直接刪除會影響之前的解決方法是深拷貝
// delete this.state.isRead;
// 深拷貝state
var newState = JSON.parse(JSON.stringify(this.state));
delete newState.isRead;
console.log(newState);
// user_login(this.state).then((res)=>{
// })
}
render() { //渲染組件模板到視圖
return (
<div>
{/* 非受控元素變成受控元素,通過value和onChange綁定實現 */}
{/* value綁定,將組件狀態(tài)綁定到元素的value屬性 */}
{/* onChange綁定,當元素的值發(fā)生改變時更新元素的值到組件狀態(tài) */}
<input type="text" name="phone" value={this.state.phone} onChange={(e) => { this.handleChange(e) }} placeholder='請輸入手機號' /><br />
<input type="password" name="pass" value={this.state.pass} onChange={(e) => { this.handleChange(e) }} placeholder='請輸入密碼' />
<input type="checkbox" name="isRead" value={this.state.isRead} onChange={(e) => { this.handleChange(e) }} />
</div>
);
}
}
export default App;
到此這篇關于React組件的使用詳細講解的文章就介紹到這了,更多相關React組件內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
React Native預設占位placeholder的使用
本篇文章主要介紹了React Native預設占位placeholder的使用,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
React+ResizeObserver實現自適應ECharts圖表
ResizeObserver是JavaScript的一個API,用于監(jiān)測元素的大小變化,本文主要為大家介紹了React如何利用ResizeObserver實現自適應ECharts圖表,需要的可以參考下2024-01-01

