【问题标题】:React Hooks: Hide/Show elements from other componentsReact Hooks:隐藏/显示其他组件的元素
【发布时间】:2019-12-12 02:25:22
【问题描述】:

我有一个具有全局导航的项目。导航内部是一个按钮,应该能够隐藏具有“en”类的某些元素。

nav.js 文件中

这是按钮的代码

<Button id="switch-lang" onClick={translate}>ENGLISH</Button>

这是我目前拥有的功能

function translate(){
        const handleSwitchLang = (dataLang) => {
            if (lang === switchedLang){
                setSwitchLang('');
            } else {
                setSwitchLang(dataLang);
            }
        };
    }

context.js

export const SwitchLangContext = createContext();

在我的homecontent.js


    const [switchedLang, setSwitchLang = useState(true);

    const context = useContext(SwitchLangContext);

这应该是我要隐藏的 div

<div className="en">
 This is my planned content
</div>

我很不确定如何在 React Hooks 中隐藏类为 'en' 的元素。我做了类似的事情,但它在同一个文件上。现在这些在两个不同的文件上,我很不确定如何。

【问题讨论】:

    标签: javascript reactjs react-hooks


    【解决方案1】:

    基于 props 隐藏元素的一种方法是这样做:

    const MyComponent = (props) => {
        const contentNode = null;
        if (props.switchedLang === true) {
            contentNode = (
                <div className="en">
                    This is my planned content
                </div>
            );
        }
    
        return (
            <React.Fragment>
                {contentNode}  
            </React.Fragment>
        );
    }
    

    或者,可以将 CSS 类应用于隐藏它们的父级。

    .lang-switched .en {
        visibility: hidden;
        // or
        display: none;
    }
    

    然后

    <div className={`content${props.switchedLang && ' lang-switched')`}>
        <div className="en">
            This is my planned content
        </div>
        ...
    </div>
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-09
      • 1970-01-01
      • 2014-08-21
      相关资源
      最近更新 更多