【问题标题】:Toggle between two divs or text using React hooks使用 React 钩子在两个 div 或文本之间切换
【发布时间】:2020-07-12 15:59:28
【问题描述】:

首先,我是 React 和 Hooks 的新手。

我想做的是,当状态发生变化时,div 或某些文本也会发生变化。

例如:

const App = ( ) => {

    const [textToggle, textToggleState] = useState(true)

    return (

        <div>This is come text</div>
        <div>This is come extra text</div>
        <div onClick={ () => textToggleState(!textToggle) }>Click me</div>
    );
};

export default memo(App);

所以在这种情况下,我有我的切换按钮,它将在真或假状态之间切换。我通常使用它来从 div 中添加/删除一个类,例如:

<div className={textToggle ? "normal-class" : "super-class"}></div>

或类似的东西。但是,我想要实现的是在上述代码中显示两个第一个 div 之间进行更改,或者在启动切换时只在第一个 div 中添加单词extra

我不太确定如何实现这一点,甚至是否应该使用useState 函数。

【问题讨论】:

    标签: reactjs react-hooks


    【解决方案1】:

    如果你只想相应地显示/隐藏每个 div,试试这个

    {textToggle && <div>This is come text</div>}
    {!textToggle && <div>This is come extra text</div>}
    

    或简化

    {
     textToggle ?
      <div>This is come text</div>
     :
      <div>This is come extra text</div>
    }
    

    如果你想添加 extra 文本,那么试试这个

    <div>This is come {textToggle ? "" : "extra"} text</div>
    

    【讨论】:

    • 啊,我不知道它可以这样使用。很棒。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多