简体   繁体   中英

Toggle CSS style in a functional React component

Every post or tutorial on how to toggle css in React assumes that I'm using a class component. However, I'm using a functional component and don't have access to this and state . Can somebody tell me how to toggle a CSS style for a JSX element in a React functional component?

import React from 'react';
import { Row, Container, Col } from 'react-bootstrap';

const FilterBar = ( {eventFilters, setEventFilters} ) => {
  

  const someFunction = () => {
      // code in here
  }  

  return(
    <div className="row-fluid" >
      <Container fluid >
        <Row className="justify-content-md-center mb-2 mt-2">
          <Col onClick={someFunction}> <button value="ALL"> All </button> </Col>   
          <Col onClick={someFunction}> <button value="WORKSHOP"> Workshop </button> </Col>        
          <Col onClick={someFunction}> <button value="MINIEVENT"> Minievent </button> </Col>        
        </Row>
        <Row className="justify-content-md-center mb-2">  
          <Col onClick={someFunction}> <button value="SPEAKER"> Speaker </button></Col>
          <Col onClick={someFunction}> <button value="MEAL"> Meal </button> </Col>
          <Col onClick={someFunction}> <button value="OTHER"> Other </button> </Col>     
        </Row>
      </Container>
    </div>
  );
}

export default FilterBar; 

Toggling some style via click event object. You can use the event target style property to change the current textDecoration property to "line-through" or nothing ("").

const toggleStrikethrough = (e) => {
  e.target.style.textDecoration =
    e.target.style.textDecoration === "line-through" ? "" : "line-through";
};

编辑 toggle-css-style-in-a-functional-react-component

function App() {
  const toggleStrikethrough = (e) => {
    e.target.style.textDecoration =
      e.target.style.textDecoration === "line-through" ? "" : "line-through";
  };

  return (
    <div className="App">
      <div onClick={toggleStrikethrough}>ALL</div>
      <div onClick={toggleStrikethrough}>WORKSHOP</div>
      <div onClick={toggleStrikethrough}>MINIEVENT</div>
      <div onClick={toggleStrikethrough}>SPEAKER</div>
      <div onClick={toggleStrikethrough}>MEAL</div>
      <div onClick={toggleStrikethrough}>OTHER</div>
    </div>
  );
}

Note: This is generally frowned upon though and considered an anti-pattern as you are directly manipulating the DOM. The better and more react way is to maintain a toggled "state" in local component state for each element you want to toggle style ( or anything really ) of.

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