简体   繁体   中英

Meteor and React: Correct way to manipulate elements on click?

I'm learning application development with Meteor and React and have run into a hurdle. I want users to be able to click on an element and have that change the class of another element. If I was creating a site without Meteor or React I would use a jQuery function like this:

$("#button").click(function(){
  $("#target").removeClass("hidden");
});

I can't seem to figure out how to use jQuery in my React application (but copying the code into chrome web console works) so I started googling and found that it isn't recommended to use jQuery or to directly manipulate the DOM at all while using React. I don't understand much of how React's virtual DOM works at this stage.

So my question is: what is the correct way to replicate what this jQuery code does in a React application?

I recommend You to combine classnames ( link ) and state, so You can do it like this:

class Example extends React.Component {
  constructor() {
    super();
    this.state = {
      clicked: false
    };
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    this.setState({ clicked: true });
  }
  render() {
    return (
      <div className={classNames('foo', { hidden : this.state.clicked })}>
        <button onClick={this.handleClick} >BUTTON</button>
      </div>
    );
  }
}

ReactDOM.render(
  <Example />,
  document.getElementById('example')
);

If state clicked is false , class hidden is not active on a specific element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM