react一个框选插件的使用吧。。.。(获取时间戳)

先给代码放这里 后续再整理吧

通过插件获取时间戳 1为选中 0为未选中

插件支持框选 以及框选获得框选的id 支持点击选中再次点击取消选中
对插件进行二次修改
先给插件地址附上git地址

下面就是具体代码了


import Selection from './Selection'
import React, { Component } from 'react'

import {WeektimeFilter} from "../../api/filters"

// const content = [...Array(7)].map((item, row) => {
//   return [...Array(14)].map((item, col) => {
//     const data = Math.floor(Math.random() * 100 + 1)
//     const tmp = <h3 key={`${row}-${col}`}>{data}</h3>
//     return tmp
//   })
// })
export default class Test extends Component {
    state = {
        arr:[],
        // str: "111111111111111110000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111",
    }
 
  componentWillUnmount () {
    
    }
    handleMouseEnter(e){
        console.log(e)
    }
  mounted = all => { //all items(dom)
    // console.log('allalllallallall',all)
    if (this.state.str){
        for (var g = 0; g <= all.length-1; g++){
            console.log(this.state.str[g])
            // for (var i = 0; i <= this.state.str.length-1; i++){
                if(this.state.str[g] ==1){
                    console.log(this.state.str[g])
                    all[g].style.backgroundColor="red"
                }else{
                    console.log(this.state.str[g])
                    all[g].style.backgroundColor="" 
                }
        } 
    }
        var arr=[]
        for(var i=0; i <=6; i++){
                arr[i]=[];
            for(var j = 0; j <= 47; j++){
                
                arr[i][j]= 0;
            }
            // arr[i]=0
        console.log(arr)
        }
        this.setState({
            arr:arr
        },()=>{
            // console.log(this.state.arr)
        })
    
  }
  selected = (positions, items, all) => { //data-position(array of string),selected items(array of dom)
    console.log(typeof positions,positions)
    if(positions.length==336){
        for (var g = 0; g <= items.length-1; g++){
            items[g].style.backgroundColor="" 
        }
        // this.setState(
        //     {
        //         str:'000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
        //     }
        // )
    }else{
        for (var g = 0; g <= items.length-1; g++){
        if(items[g].style.backgroundColor=="" ){
            items[g].style.backgroundColor="red"
        }else{
            items[g].style.backgroundColor="" 
        }
    //   console.log(typeof items,items[g])  
    }
    
        var ar=this.state.arr
        for(var y=0;y<positions.length; y++){
            var z=positions[y].split("-")
            // console.log(positions[y])
            // console.log( positions[y].split("-"))
            // console.log(ar)
            if(ar[z[0]][z[1]]==1){
                ar[z[0]][z[1]]=0
            }else {     
            ar[z[0]][z[1]]=1
            }
            // ar[z[0]][z[1]]=1
        }
        var str=ar.flat(1).join('')
        console.log(str)
        this.setState({
            arr:ar
        },
        ()=>console.log(this.state.arr)
        )
    }
    
  }
    fun_date=(num)=> { 
        var date1 = new Date();
        //今天时间
        var time1 = date1.getFullYear() + "-" + (date1.getMonth() + 1) + "-" + (date1.getDate()<10?'0'+date1.getDate():date1.getDate())
        // console.log(time1);
        var date2 = new Date(date1);
        date2.setDate(date1.getDate() + num);
        var time2 = date2.getFullYear() + "-" + (date2.getMonth() + 1) + "-" + (date2.getDate()<10?'0'+date2.getDate():date2.getDate()
        ); 
        // console.log(time2);
        return time2;
    }
  cleartimes=()=>{
      this.setState(
          {
              str:'000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'
          }
      )
      
  }
  singleSelected = (position, item, all) => { //data-position(string),selected items(dom
    console.log(typeof position,position)
    if(position){
        var ar=this.state.arr
    var z=position.split("-")

            // ar[z[0]][z[1]]=1

        // console.log(position,ar, z[0],z[1])
            if(ar[z[0]][z[1]]== 1){
                
                if(item.style){
                    item.style.backgroundColor="" 
                    ar[z[0]][z[1]]=0
                }else{
                    // item.style.backgroundColor="red"
                    for (var g = 0; g <= item.length-1; g++){
                        if(item[g].style.backgroundColor=="" ){
                            item[g].style.backgroundColor="red"
                            ar[z[0]][z[1]]=1
                        }else{
                            item[g].style.backgroundColor="" 
                            ar[z[0]][z[1]]=0
                        }
                    //   console.log(typeof item,item[g])  
                    }
                }
                
            }else{ 
                if(item.style){
                    item.style.backgroundColor="red" 
                    ar[z[0]][z[1]]=1
                }else{
                    for (var g = 0; g <= item.length-1; g++){
                        if(item[g].style.backgroundColor=="" ){
                            item[g].style.backgroundColor="red"
                            ar[z[0]][z[1]]=1
                        }else{
                            item[g].style.backgroundColor="" 
                            ar[z[0]][z[1]]=0
                        }
                    //   console.log(typeof item,item[g])  
                    }
                    // item.style.backgroundColor=""
                }
            }
    
    this.setState({
        arr:ar
    },
    // ()=>console.log(this.state.arr)
    )
    }
  }
  
  leaved = (position, item) => {
    console.log(position)
  }
  
    
  
    render() {
        return (
            <div style={{paddingTop:'60px'}} >
                <Selection
                    cols={48} 
                    rows={7} 
                    width={16} 
                    height={30} 
                    gap={0} 
                    wrapperScroll={undefined}
                    onMounted={this.mounted}
                    onMouseEnter={this.handleMouseEnter.bind(this)}
                    // onHovered={this.hovered}
                    // onLeaved={this.leaved}
                    onSelected={this.selected}
                    onSingleSelected={this.singleSelected}
                    itemClass="selection_item"
                    // extraClass={['claa',]}
                    activeClass="selection_item_active"
                />
                <div ></div>
                        
                <div>
                
                    <span><span style={{width:10,height:10,background:'#0582CE',fontSize:'10',color:'#0582CE'}}>22</span>&nbsp;已选</span>
                    <span><span style={{width:10,height:10,background:'#0582CE',fontSize:'10',color:'#0582CE'}}>22</span>&nbsp;已选</span>
                </div>
                
                    <button onClick={this.cleartimes} > 清除</button>        
                            
              
              <style>{`
              
              table{
                cellspacing:0;
              }
              .claa{
                  background:red
              }
              
              .table{
                cellspacing:0;
                width:75%;
                color:#fff;
                border: 1px
              }
              th,td{
                  height:30px;
                  text-align:center;
                  color:#fff;
              }
              .titlewidth{
                  width:32px;
              }
              .table {  width: 990px;  height: 850px;  }
              .table tr {  height: 50px;  overflow: scroll  }
              .table-container {
                  position: absolute;
                  top: 0;
                  left: 200px;
                  height: 750px;
                  width: 990px;
                  overflow-y: scroll;
                  overflow-x: hidden;
              }
               #title {  background-color: #BDE4F4;  }
              .fileDiv {  background-color:#FEFF89; }
              .seled {  border: 1px solid red;  background-color: #D6DFF7;  }
              `}</style>
            </div>
          )
    }
}


select文件

import PropTypes from 'prop-types'

import './Selection.css'
import { getTop, getLeft, clearEventBubble, scroll, isInPath, getParents } from './utils'
import { Tooltip } from 'antd'
const dateList = [
  '一','二','三','四','五','六','日',
]

class Selection extends React.Component {
  static propTypes = {
    cols: PropTypes.number,
    rows: PropTypes.number,
    width: PropTypes.number,
    height: PropTypes.number,
    gap: PropTypes.number,
    wrapperScroll: PropTypes.object,
    itemClass: PropTypes.string,
    extraClass: PropTypes.array,
    activeClass: PropTypes.string,
    onMounted: PropTypes.func,
    onHovered: PropTypes.func,
    onLeaved: PropTypes.func,
    onSelected: PropTypes.func,
    onSingleSelected: PropTypes.func,
  }

  constructor(props) {
    super(props)
    this.state = {
      cols: props.cols || 24,
      rows: props.rows || 7,
      width: props.width || 30,
      height: props.height || 50,
      margin: props.gap || 0,
      isMouseDown: false,
      templates: [...Array(props.rows || 7)].map(item => [...Array(props.cols || 24).keys()]),
      allItems: [],
      selectedItems: [],
      selectedPostions: [],
      selectEle: {
        width: 0,
        height: 0,
        top: 0,
        left: 0,
        display: 'none'
      }
    }
    this.selectionTable = null
  }
componentDidMount () {
    const { onMounted } = this.props
    const table = this.selectionTable

    const allItems = [...table.getElementsByTagName('td')]

    onMounted && onMounted(allItems)
    this.setState({ allItems })
  }

  componentWillUnmount () {
    this.setState({ allItems: null, selectedItems: null })
    this.setState = () => { }
  }
  addActiveClass = target => {
    const { activeClass } = this.props

    target.classList.add(activeClass || 'selection_item_active')
  }

  removeActiveClass = target => {
    const { activeClass } = this.props

    target.classList.remove(activeClass || 'selection_item_active')
  }

  

  down = e => {
    clearEventBubble(e)
    const { selectEle } = this.state
    const { wrapperScroll } = this.props

    const { clientX, clientY } = e

    const top = getTop(e.currentTarget)
    const left = getLeft(e.currentTarget)
    const { scrollTop, scrollLeft } = wrapperScroll || scroll()

    const startX = clientX - left + scrollLeft
    const startY = clientY - top + scrollTop

    selectEle.left = startX
    selectEle.top = startY

    this.setState({ isMouseDown: true, startX, startY, selectEle })
  }
  move = e => {
    clearEventBubble(e)
    const { isMouseDown, selectEle, startX, startY, selectedItems, selectedPostions } = this.state
    const { wrapperScroll } = this.props

    if (!isMouseDown) return

    const top = getTop(e.currentTarget)
    const left = getLeft(e.currentTarget)
    const { scrollTop, scrollLeft } = wrapperScroll || scroll()

    const { clientX, clientY } = e
    const _x = clientX - left + scrollLeft
    const _y = clientY - top + scrollTop

    selectEle.left = Math.min(_x, startX)
    selectEle.top = Math.min(_y, startY)
    selectEle.width = Math.abs(_x - startX)
    selectEle.height = Math.abs(_y - startY)
    selectEle.display = 'block'

    const items = [...e.currentTarget.getElementsByTagName('td')]
    selectedPostions.length = 0
    selectedItems.length = 0

    items.forEach(item => {
      this.removeActiveClass(item)

      if (isInPath(item, selectEle)) {
        this.addActiveClass(item)

        selectedPostions.push(item.dataset['position'])
        selectedItems.push(item)
      }
    })

    this.setState({ selectEle, selectedItems, selectedPostions })

  }
  up = e => {
    clearEventBubble(e)
    const { allItems, selectEle, selectedPostions, selectedItems } = this.state
    const { onSelected, onSingleSelected } = this.props
    const target = e.target.tagName === 'TD' ? e.target : getParents(e.target, 'TD')

    selectEle.left = 0
    selectEle.top = 0
    selectEle.width = 0
    selectEle.height = 0
    selectEle.display = 'none'

    allItems.forEach(item => {
      this.removeActiveClass(item)
    })

    if (selectedPostions.length === 0) {
      onSingleSelected && onSingleSelected(target.dataset['position'], target, allItems)
    } else if (selectedPostions.length === 1) {

      onSingleSelected && onSingleSelected(selectedPostions[0], selectedItems, allItems)
    } else {
      onSelected && onSelected(selectedPostions, selectedItems, allItems)
    }

    this.setState({ isMouseDown: false, selectEle, selectedPostions: [] })
  }

  over = e => {
    clearEventBubble(e)
    const { onHovered } = this.props
    const target = e.target.tagName === 'TD' ? e.target : getParents(e.target, 'TD')

    this.addActiveClass(target)
    onHovered && onHovered(target.dataset['position'], target)
  }
  leave = e => {
    clearEventBubble(e)
    const { isMouseDown } = this.state
    const { onLeaved } = this.props
    const target = e.target.tagName === 'TD' ? e.target : getParents(e.target, 'TD')

    !isMouseDown && this.removeActiveClass(target)
    onLeaved && onLeaved(target.dataset['position'], target)
  }

  render () {
    const { templates, selectEle, width, height, cols, rows, margin } = this.state
    const { children, itemClass, extraClass } = this.props
    const self = this

    return (
      <div
        className='selection_wrapper'
        style={{
          width: cols * width + margin * (1 + cols),
          height: rows * height + margin * (1 + rows),
        }}
        onMouseDown={this.down}
        onMouseMove={this.move}
        onMouseUp={this.up}
      >
        <div className='selection_element' style={{ ...selectEle }} />
        <table
          className='selection_content'
          border="1"
          cellSpacing="0"
          cellPadding="0"
          ref={ele => this.selectionTable = ele}
        >
          <tbody>
            {
              templates.map(function (rows, row) {
                return (
                  <tr key={`row-${row}`}>
                    {
                      rows.map(function (col) {
                        const className = `${itemClass || 'selection_item'} ${extraClass ? extraClass.join(' ') : ''}`

                        return (
                          <Tooltip 
                            title={`星期${dateList[row]} ${Math.floor(col / 2)}:${(col % 2) * 30 || '00'}`} 
                            placement="bottomRight"
                          >
                            <td
                              onMouseOver={self.over}
                              onMouseLeave={self.leave}
                              onClick={self.single}
                              className={className}
                              style={{ width, height, margin: `${margin}px ${margin}px 0 ${margin}px` }}
                              key={`col-${col}`}
                              data-position={`${row}-${col}`}
                            >
                              {
                                (children && children[row]) ? children[row][col] || '' : ''
                              }
                            </td>
                          </Tooltip>
                        )
                      })
                    }
                  </tr>
                )
              })
            }
          </tbody>
        </table>
      </div>
    )
  }
}

export default Selection

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值