欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

React组件内事件传参实现tab切换的示例代码

程序员文章站 2023-10-26 17:28:28
本文介绍了react组件内事件传参实现tab切换的示例代码,分享给大家,具体如下: 组件内默认onclick事件触发函数actionclick, 是不带参数的,...

本文介绍了react组件内事件传参实现tab切换的示例代码,分享给大家,具体如下:

  1. 组件内默认onclick事件触发函数actionclick, 是不带参数的,
  2. 不带参数的写法: 如onclick= { actionitem }
  3. 带参数的写法, onclick = { this.activatebutton.bind(this, 0) }

下面是一个向组件内函数传递参数的小例子

需求: 在页面的底部, 有四个按钮, 负责切换内容, 当按钮被点击时, 变为激活状态, 其余按钮恢复到未激活状态

分析: 我们首先要创建点击事件的处理函数, 当按钮被点击时, 将按钮的id作为参数发送给处理函数, 处理函数激活对应当前id的按钮, 并将其余三个按钮调整到未激活状态

实现: 用组件state创建一个含有四个元素的一维数组, 四个元素默认为零, 但界面中某个按钮被点击时, 组件内处理函数将一维数组内对应元素变为1, 其它元素变为0

效果演示:

React组件内事件传参实现tab切换的示例代码

核心代码:

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);
    }

    // 根据参数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"));

小结

React组件内事件传参实现tab切换的示例代码

上面的例子也可以通过event.target.value快速实现,但这个demo的扩展性更好, 在版本迭代过程中, 我们可以传递数量更多的参数, 详尽的描述ui层当前的状态, 方便业务的扩展

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。