React組件內(nèi)事件傳參實現(xiàn)tab切換的示例代碼
本文介紹了React組件內(nèi)事件傳參實現(xiàn)tab切換的示例代碼,分享給大家,具體如下:
- 組件內(nèi)默認onClick事件觸發(fā)函數(shù)actionClick, 是不帶參數(shù)的,
- 不帶參數(shù)的寫法: 如onClick= { actionItem }
- 帶參數(shù)的寫法, onClick = { this.activateButton.bind(this, 0) }
下面是一個向組件內(nèi)函數(shù)傳遞參數(shù)的小例子
需求: 在頁面的底部, 有四個按鈕, 負責切換內(nèi)容, 當按鈕被點擊時, 變?yōu)榧せ顮顟B(tài), 其余按鈕恢復到未激活狀態(tài)
分析: 我們首先要創(chuàng)建點擊事件的處理函數(shù), 當按鈕被點擊時, 將按鈕的id作為參數(shù)發(fā)送給處理函數(shù), 處理函數(shù)激活對應(yīng)當前id的按鈕, 并將其余三個按鈕調(diào)整到未激活狀態(tài)
實現(xiàn): 用組件state創(chuàng)建一個含有四個元素的一維數(shù)組, 四個元素默認為零, 但界面中某個按鈕被點擊時, 組件內(nèi)處理函數(shù)將一維數(shù)組內(nèi)對應(yīng)元素變?yōu)?, 其它元素變?yōu)?
效果演示:

核心代碼:
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import './index.scss'
class TabButton extends React.Component {
constructor(props) {
super(props);
this.state = {
markArray: [0, 0, 0, 0],
itemClassName:'tab-button-item'
};
this.activateButton = this.activateButton.bind(this);
}
// 根據(jù)參數(shù)id, 來確定激活四個item中的哪一個
activateButton(id) {
let tmpMarkArray = [0, 0, 0, 0]
tmpMarkArray[id] = 1;
this.setState({markArray: tmpMarkArray});
}
render() {
return (
<div className = "tab-button" >
<div className = {(this.state.markArray)[0] ? "tab-button-item-active" : "tab-button-item" } onClick = { this.activateButton.bind(this, 0) } > 零 </div>
<div className = {(this.state.markArray)[1] ? "tab-button-item-active" : "tab-button-item" } onClick = { this.activateButton.bind(this, 1) } > 壹 </div>
<div className = {(this.state.markArray)[2] ? "tab-button-item-active" : "tab-button-item" } onClick = { this.activateButton.bind(this, 2) } > 貳 </div>
<div className = {(this.state.markArray)[3] ? "tab-button-item-active" : "tab-button-item" } onClick = { this.activateButton.bind(this, 3) } > 叁 </div>
</div>)
}
}
ReactDOM.render( < TabButton / > , document.getElementById("root"));
小結(jié)

上面的例子也可以通過event.target.value快速實現(xiàn),但這個demo的擴展性更好, 在版本迭代過程中, 我們可以傳遞數(shù)量更多的參數(shù), 詳盡的描述UI層當前的狀態(tài), 方便業(yè)務(wù)的擴展
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
在create-react-app中使用css modules的示例代碼
這篇文章主要介紹了在create-react-app中使用css modules的示例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07
詳解React開發(fā)中使用require.ensure()按需加載ES6組件
本篇文章主要介紹了詳解React開發(fā)中使用require.ensure()按需加載ES6組件,非常具有實用價值,需要的朋友可以參考下2017-05-05
React-Router v6實現(xiàn)頁面級按鈕權(quán)限示例詳解
這篇文章主要介紹了使用 reac+reactRouter來實現(xiàn)頁面級的按鈕權(quán)限功能,這篇文章分三部分,實現(xiàn)思路、代碼實現(xiàn)、踩坑記錄,有需要的朋友可以借鑒參考下,希望能夠有所幫助2023-10-10
更強大的React 狀態(tài)管理庫Zustand使用詳解
這篇文章主要為大家介紹了更強大的React 狀態(tài)管理庫Zustand使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-10-10

