如何在反应组件中的mousedown / mouseup上切换类?

时间:2018-05-04 12:34:17

标签: javascript reactjs

我尝试在反应组件中切换一个类,如果用户将鼠标按下按钮,那么它会向该按钮添加一个类,当用户使用他的鼠标时,则它会恢复并从按钮中删除该类。

根据官方ReactJS文档here中的解释和示例,我设法将以下代码段放在一起,但它无法正常工作并且不断在控制台上抛出语法错误:

import React from 'react';

export class Buttons extends React.Component{

    toggleClass() {
        if this.classList.has('btnDown') {
            this.classList.remove('btnDown');
        } else {
            this.classList.add('btnDown');
        }
    }


    render(){
        return (
            <div className="btn-wrap">
                <button onMouseDown={(e) => this.toggleClass(e)} onMouseUp={(e) => this.toggleClass(e)} value = '1' >1</button>
                <button onMouseDown={(e) => this.toggleClass(e)} onMouseUp={(e) => this.toggleClass(e)} value = '2' >2</button>
                <button onMouseDown={(e) => this.toggleClass(e)} onMouseUp={(e) => this.toggleClass(e)} value = '3' >3</button>
                <button onMouseDown={(e) => this.toggleClass(e)} onMouseUp={(e) => this.toggleClass(e)} value = '4' >4</button>
                <button onMouseDown={(e) => this.toggleClass(e)} onMouseUp={(e) => this.toggleClass(e)} value = '5' >5</button>
                <button onMouseDown={(e) => this.toggleClass(e)} onMouseUp={(e) => this.toggleClass(e)} value = '6' >6</button>
            </div>
        )
    }
}

UPDATE:

我使用@ TomaszMularczyk的答案重写组件以使用react state作为参考,但现在所有按钮都被切换而不是单击按钮,如下所示: https://jsfiddle.net/69z2wepo/183164/

4 个答案:

答案 0 :(得分:2)

您可以制作自己的Button组件

**Header**
POST http://domain.de:port/.../finishprocess.xhtml HTTP/1.1
Accept: text/html, application/xhtml+xml, image/jxr, */*
Accept-Encoding: gzip
Accept-Language: en-US
Content-Type: application/x-www-form-urlencoded
Pragma: no-cache
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko
Host: domain.de:port
Content-Length: 305
Cookie: JSESSIONID=...
**Body**
Form:buttonFinishProcess=Finish process

然后使用那些而不是html按钮 -

class Button extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isDown: false
    };
  }

  toggleClass() {
    this.setState(prevState => ({ isDown: !prevState.isDown }));
  }  

  render() {
    const className = `${this.state.isDown ? "btnDown" : ""}`;
    return <button className={className} onMouseDown={e => this.toggleClass(e)} value={this.props.value} {...this.props}>{this.props.children}</button>
  }
}

答案 1 :(得分:1)

var fullAddress = []; for (var i = 0; i < place.address_components.length; i++) { var addressType = place.address_components[i].types[0]; if (componentForm[addressType]) { var val = place.address_components[i][componentForm[addressType]]; document.getElementById(addressType).value = val; } if (addressType == "street_number") { fullAddress[0] = val; } else if (addressType == "route") { fullAddress[1] = val; } } document.getElementById("lat").value = place.geometry.location.lat(); document.getElementById("lng").value = place.geometry.location.lng(); document.getElementById('fullAddress').value = fullAddress.join(" "); if (document.getElementById('fullAddress').value !== "") { document.getElementById('fullAddress').disabled = false; } } 不是HTML元素,而是React Object实例。

我会尝试更多反应方式来实现这一点并使用this

state

答案 2 :(得分:1)

不使用this内的toggleClass,而是使用事件对象:

class Buttons extends React.Component {
    toggleClass(e) {
      if(e.target.classList.contains('btnDown')) {
        e.target.classList.remove('btnDown');
      } else {
        e.target.classList.add('btnDown');
      }
    }

    render() {
      return (
        <div className="btn-wrap">
          <button onMouseDown={(e) => this.toggleClass(e)} onMouseUp={(e) => this.toggleClass(e)} value = '1' >1</button>
          <button onMouseDown={(e) => this.toggleClass(e)} onMouseUp={(e) => this.toggleClass(e)} value = '2' >2</button>
          <button onMouseDown={(e) => this.toggleClass(e)} onMouseUp={(e) => this.toggleClass(e)} value = '3' >3</button>
        </div>
      )
    }
}

css取自@Tomasz Mularczyk的答案。

jsfiddle

答案 3 :(得分:0)

我稍微改写了你的代码,它应该现在正常工作:

class Buttons extends React.Component {

     constructor(props) {
         super(props);
         this.state = {
         isDown: null
      };

  }

  pressButton = (i) => {
    this.setState({ isDown: i });
  };
  releaseButton = () => {
    this.setState({ isDown: null });
  };

  render() {
    const { isDown } = this.state;
    const buttons = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, '+', '-'];

    return (
      <div className="btn-wrap">
        {buttons.map((button, i) => (
          <button
            className={`${isDown === i ? 'btnDown' : ''}`}
            onMouseDown={this.pressButton.bind(undefined, i)}
            onMouseUp={this.releaseButton}
            value={button}
          >
            {button}
          </button>
        ))}
      </div>
    )
  }
}

ReactDOM.render(
  <Buttons />,
  document.getElementById('container')
);`