首页 > 解决方案 > 在自定义点击时反应条件样式

问题描述

我试图在onClick触发事件时更改一个类,调用我的函数并且它似乎正在工作,但是该类不会更新渲染,这是我的代码:

import React from 'react';

const Something = props => {
  let opened = false;

  const toggle = () => {
    opened = !opened;
  };

  return (
    <div className={opened ? 'some-class opened' : 'some-class'}>
      <div className="some-inner-class" onClick={toggle}>
       ...content
      </div>
    </div>
  );
};

export default Something;

我只想能够在点击事件触发时更改样式。

标签: javascriptcssreactjs

解决方案


我对你的建议是在这种情况下使用反应钩子,我的意思是,像这样,我已经用我的建议更新了你的代码;希望能帮助到你;

import React, { useState }  from 'react';

const Something = props => {
  // ***because this doesn't exist in a function component and we'd want to persist this value of opened between function call, a react hook in a function component will be ideal in your case. 
  //let opened = false; 

  // *suggestion as per react documentation: useState hook lets us keep local state in a function component
  const [opened, setOpened] = useState(false);

  // ***you don't really need this part, see my approach in second div of return 
  // const toggle = () => {
  //   opened = !opened;
  // };

  return (
    <div className={opened ? 'some-class opened' : 'some-class'}>
      <div className="some-inner-class" onClick={() => setOpened(true)}>
        <p>Click me</p>
      </div>
    </div>
  );
};

export default Something;

推荐阅读