admin管理员组

文章数量:1402783

In jQuery, we can easily set toggle event like,

$('div').click(function(){
   $('div').toggleClass('active');
});

But how to implement this kind of thing in reactjs with jQuery.

In jQuery, we can easily set toggle event like,

$('div').click(function(){
   $('div').toggleClass('active');
});

But how to implement this kind of thing in reactjs with jQuery.

Share Improve this question asked Nov 18, 2015 at 12:50 SathyaSathya 1,7343 gold badges38 silver badges59 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 3

Inside your react ponent class you could have the toggle flag as part of state data this.state.toggle. render method will see use this data to add class or not. We can bind a click listener to the button to to flip the flag in state.

getInitialState: function () {
    return {
        toggle: false
    };
},

clickHandler: function () {
    this.setState({ toggle: !this.state.toggle })
},

render: function () {
    var clsName = this.state.toggle ? 'active' : '';
    return <button className={ clsName } onClick={ this.clickHandler }>{ this.props.label }</button>;
}

Hope this helps. Good luck, have fun!

To get toogling you to have to controll your state.

In this case i toggling the style attribute and you also can do it with your className attribute:

var Hello = React.createClass({
    getInitialState: function(){
        return {
          isVisible: true
        }
    },
    handleClick: function(){
        var notVisible = !this.state.isVisible;
        this.setState({
          isVisible: notVisible
        })
    },
    render: function() {
        var styleClass = this.state.isVisible? 'hidden':'visible';
        console.log(styleClass);
        return <div>
            <span style={{visibility: styleClass}}> Hello World</span>
            <button onClick={this.handleClick}>Click me</button>
        </div>;
    }
});

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

Link to fiddle

I hope i will help you.

Thanks

You can use the state for doing something like this in several ways:

first of all you need to declare the state variable in your ponenet:

getInitialState: function () {
        return {
            isActive: false
        };
}

then you will need an onClick function

handleClick: function(){
   this.setState({isActive: !this.state.isActive});
}

Now you need to use this property in you render method

Option 1: concatenating class using a "short if" form

<div
   className={this.state.isActive? "active" : ""}
   onClick={this.handleClick}
>
    Some content...
</div>

Option 2: by using the React classet addons that you can find at https://github./petehunt/react-classset

<div
   className={
        React.addons.classSet({
            active: this.state.isActive
        })
   }
   onClick={this.handleClick}
>
    Some content...
</div>

Edit: I have just found out that the option2 si deprecated and they suggest instead to use this utility:

https://github./JedWatson/classnames

https://github./JedWatson/classnames

render () {
    var btnClass = classNames({
       'btn-pressed': this.state.isPressed,
    });
    return <button className={btnClass}>{this.props.label}</button>;
}

This code toggle btn-pressed class according buttons pressed state.

In functional ponent, we can use state & setState of useState hooks. The active className rendering depends on active state. And the toggle can be done by negating the previous active state.

const CarBrand = ({ brand }) => {
    const [active, setActive] = useState(false);

    return (
        <div
            onClick={() => setActive(prevState => !prevState)}
            className={`car-brand ${active ? "active" : ""}`}
        >
            {brand}
        </div>
    )
}

Example:

const { useState } = React;

const carBrands = [
    "Audi",
    "BMW",
    "Citroen",
    "Ford",
    "Honda",
    "Jaguar",
    "Land Rover",
    "Mercedes",
    "Mini",
    "Nissan",
    "Toyota",
    "Volvo",
];

const CarBrand = ({ brand }) => {
    const [active, setActive] = useState(false);
    return (
        <div
            onClick={() => setActive(prevState => !prevState)}
            className={`car-brand ${active ? "active" : ""}`}
        >
            {brand}
        </div>
    )
}

function App() {
    return (
        <div>
            <h1>Car Brands</h1>
            <div className="car-brands">
                {carBrands.map((brand, i) => {
                    return <CarBrand key={i} brand={brand} />;
                })}
            </div>
        </div>         
    )
}

ReactDOM.render(<App />, document.querySelector('.react'));
.car-brands {
    font-family: Arial;
    color: #ffffff;
    background-color: DodgerBlue;
    width: 200px;
}

.car-brand {
    color: #ffffff;
    padding: 8px 16px;
    border: 1px solid transparent;
    border-color: transparent transparent rgba(0, 0, 0, 0.1) transparent;
    cursor: pointer;
    user-select: none;
}

.car-brand.active {
    background-color: rgba(0, 0, 0, 0.1);
}
<script crossorigin src="https://unpkg./react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg./react-dom@17/umd/react-dom.development.js"></script>

<div class='react'></div>

本文标签: javascriptHow to create toggle class event in reactjs without jqueryStack Overflow