【问题标题】:How to toggle class of a div element by clicking on a button that is inside another functional component (another file)?如何通过单击另一个功能组件(另一个文件)内的按钮来切换 div 元素的类?
【发布时间】:2020-06-27 16:18:38
【问题描述】:

我想通过单击另一个组件文件内的按钮来切换容器类(文件 2)。

该按钮已经有一个 onClick 函数,我想让它调用两个函数。按钮的两个切换功能和容器的两个类切换。

希望它有意义。

到目前为止,这是我的代码:

按钮组件(文件1)

import React, {useState} from "react";
import "./Sort.scss";

const Sort = () => {

    const [toggleSortIcon, toggleSortIconSet] = useState(false);

    return (
        <div className="tools">
            <button 
            onClick={() => toggleSortIconSet(!toggleSortIcon)} 
            className={`sort ${toggleSortIcon ? "horizontal" : "vertical"}`}>
            </button>
        </div>
    );
}

export default Sort;

我要更改类的Div容器组件(文件2)

import React, {useState} from "react";
import "./WordContainer.scss";
import UseAnimations from "react-useanimations";


const WordContainer = ({title, definition, example}) => {

  const [toggleSize, toggleSizeState] = useState(false);

  return (
    <div className={`container ${toggleSize ? "big" : "small"}`}>
      <div className="content">
        <h2>{title}</h2>
        <p>{definition}</p>
        <h3>Example</h3>
        <p>{example}</p>
      </div>
      <img onClick={() => toggleSizeState(!toggleSize)} src="./resize.svg" alt="resize" className="resize"/>
      <div className="bookmark">
        <UseAnimations
          animationKey="bookmark"
          size={26}
        />
      </div>
    </div>
  );
}

export default WordContainer;

【问题讨论】:

    标签: reactjs onclick components


    【解决方案1】:

    您可以拥有一个全局状态管理系统(redux 或带有自定义挂钩),您可以使用它来存储图标大小。

    或者您可以简单地为您的组件提供一个回调,将图标大小存储在父组件中,然后将其反馈给您的 像这样的:

    const [size, setSize] = useState(/* default value */);
    
    render() {
      <>
        <Sort onSizeToggle={setSize} />
        <WordContainer size={size} />
      </>
    }
    

    【讨论】:

    • 我是 React 新手,所以我不完全了解如何实现这一点
    • 您可能想检查第一个解决方案:medium.com/octopus-labs-london/… 至于第二个,想象有一个父组件呈现您的组件(Sort 和 WordContainer)并要求 Sort 让它知道单击按钮时,然后将新值提供给 WordContainer。我编写的代码将成为该父组件的一部分。
    • 谢谢,我去看看:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-28
    • 1970-01-01
    相关资源
    最近更新 更多