【问题标题】:How to modify DOM in React - typescript - Styled-components app with click event?如何使用点击事件修改 React - typescript - Styled-components 应用程序中的 DOM?
【发布时间】:2021-03-01 07:31:09
【问题描述】:

我有一个由 React、Typescript 和样式化组件构建的应用程序(初学者使用 typescript 和样式化组件)。我想创建一个简单的单击事件,在父组件中可见两个子组件中的哪一个之间切换。你能帮我修复我的代码或建议一种替代方法吗?

这是我在 //comment 中无法解决的部分的想法:

let flipSwitch: boolean = false;

export const myCard: React.FC<myProps> = (props) => {
  return (
    <Parent onClick={e => {
       if (!flipSwitch) {
         // dontn't know how to write this part:
         //e.get Child1 element.style.display = 'none';
         //e.get Child2 element.style.display = 'none';
         flipSwitch = true;
        } else {
         //e.get Child2 element.style.display = 'none';
         //e.get Child1 element.style.display = 'block';
         flipSwitch = false;
       }
     }
      
    }>
      
      <Child1>
          <GrandChild>{props.whatever}</GrandChild>
          <GrandChild2>{props.whatever}</GrandChild2>
      </Child1>

      <Child2>
          <GrandChild3>{props.whatever}</GrandChild3>
          <GrandChild4>{props.whatever}</GrandChild4>
      </Child2>

    </Parent>
  )
}

【问题讨论】:

    标签: reactjs typescript onclick dom-events styled-components


    【解决方案1】:

    您可以在组件本身上使用状态和条件状态:

    import React, { useState } from 'react';
    
    export const myCard: React.FC<myProps> = (props) => {
      const [flipSwitch, setFlipSwitch] = useState(false)
    
      return (
        <Parent onClick={e => setFlipSwitch(!flipSwitch)}>
          
         {flipSwitch &&
           <Child1>
              <GrandChild>{props.whatever}</GrandChild>
              <GrandChild2>{props.whatever}</GrandChild2>
           </Child1>
         }
    
        {!flipSwitch &&
          <Child2>
              <GrandChild3>{props.whatever}</GrandChild3>
              <GrandChild4>{props.whatever}</GrandChild4>
          </Child2>
        }
    
        </Parent>
      )
    }
    

    我真的不知道应该在你的代码上显示哪一个,但只是玩弄那个^^

    【讨论】:

      猜你喜欢
      • 2021-08-07
      • 2021-11-25
      • 2020-11-13
      • 2022-01-26
      • 2020-02-16
      • 2021-01-09
      • 2017-11-18
      • 2022-07-29
      • 2021-08-04
      相关资源
      最近更新 更多