在函数 React 组件中切换 CSS 样式

每篇关于如何在 React 中切换 css 的帖子或教程都假定我使用的是类组件。但是,我使用的是功能组件,无法访问this和state。有人能告诉我如何在 React 函数组件中切换 JSX 元素的 CSS 样式吗?


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; 


aluckdog
浏览 152回答 1
1回答

叮当猫咪

通过点击事件对象切换一些样式。您可以使用事件目标样式属性将当前textDecoration属性更改为“直通”或无(“”)。const toggleStrikethrough = (e) => {&nbsp; e.target.style.textDecoration =&nbsp; &nbsp; e.target.style.textDecoration === "line-through" ? "" : "line-through";};function App() {&nbsp; const toggleStrikethrough = (e) => {&nbsp; &nbsp; e.target.style.textDecoration =&nbsp; &nbsp; &nbsp; e.target.style.textDecoration === "line-through" ? "" : "line-through";&nbsp; };&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; <div onClick={toggleStrikethrough}>ALL</div>&nbsp; &nbsp; &nbsp; <div onClick={toggleStrikethrough}>WORKSHOP</div>&nbsp; &nbsp; &nbsp; <div onClick={toggleStrikethrough}>MINIEVENT</div>&nbsp; &nbsp; &nbsp; <div onClick={toggleStrikethrough}>SPEAKER</div>&nbsp; &nbsp; &nbsp; <div onClick={toggleStrikethrough}>MEAL</div>&nbsp; &nbsp; &nbsp; <div onClick={toggleStrikethrough}>OTHER</div>&nbsp; &nbsp; </div>&nbsp; );}注意:虽然这通常是不受欢迎的,并且被认为是一种反模式,因为您正在直接操作 DOM。更好和更反应的方法是为每个要切换样式(或任何真正的)的元素在本地组件状态中保持切换的“状态” 。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript