Check for existence of classes on click (React)

巧了我就是萌 提交于 2021-02-18 06:29:13

问题


I want to check to see if a particular element, when clicked, has a specified class. I know that you can bind a click handler which passes e.target to the handler. My thinking was to get e.target.classList.indexOf(this.myClass) > -1 to see if it has the class, but I get the following error.

e.target.classList.indexOf is not a function

I assume this is because classList is an array-like object, and not an actual array. Is there a simpler way to get a list of classes from a clicked element in React without performing all of the "slice call" magic?

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        this.myClass = 'my-class';
    }

    handleClick(e) {
        // check if e.target class has this.myClass
        if (/* logic */) {
            // perform action
        }
    }

    render() {
        return <div onClick={this.handleClick.bind(this)} className={this.myClass + ' other-class'}>
            <div>My Component</div>
        </div>
    }

}

How can I get an array of classes from the "target" element of a click in React's event system?


回答1:


Element.classList provides a contains() function which should solve your issue:

e.target.classList.contains(this.myClass)

Docs


Also note that this may not be what you think it is in your event handler, unless you bind the function context explicitly, e.g. using bind().




回答2:


You can use .contains method.,

contains( String ) Checks if specified class value exists in class attribute of the element.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myClass = 'my-class';
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(e) {
    console.log(e.currentTarget.classList.contains(this.myClass))
  }

  render() {
    return <div 
      className={this.myClass + ' other-class'} 
      onClick={this.handleClick}
    >
      <div>My Component</div>
    </div>
  }
}


ReactDOM.render(
  <MyComponent name="World" />,
  document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>


来源:https://stackoverflow.com/questions/38795892/check-for-existence-of-classes-on-click-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!