【问题标题】:How to change z index of components in React?如何更改 React 中组件的 z 索引?
【发布时间】:2020-12-11 12:14:56
【问题描述】:

我从 Angela Yu 的 Udemy 课程中分叉了 Keeper 应用程序项目,并进行了一些修改。这是链接:https://codesandbox.io/s/keeper-app-part-2-completed-forked-9zks1?file=/src/components/Note.js

我希望能够在画布上移动笔记,虽然我能够做到这一点,但我在堆叠笔记时遇到了问题。我希望所选笔记位于所有其他笔记之上。我尝试通过创建一个名为 noteRef 的 useRef 并输入以下内容来修改 z-index 值:

noteRef.current.style.zIndex = 9999

在 onMouseDown 期间调用的 handleOnClick 函数内部。然而,它并没有真正做任何事情。我试过了,然后输入

noteRef.current.style.zIndex = 1

在 handleOnUp 函数中,虽然我可以在移动时将选定的音符放在其他音符之上,但显然当我释放鼠标时它会回到音符的正下方。

我也尝试过使用 useEffect 但它也没有改变任何东西。我想知道是否有办法从 App 组件(笔记组件所在的位置)访问函数。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    **已编辑 Here 是我的示例代码沙箱。

    在父组件中管理notes的z-index怎么样?

    在下面的示例中,我在App 组件中使用了useState,并制作了stackNote 函数来处理子组件的样式。

    function App () {
      const [zIndex, setZindex] = useState(1);
      const stackNote = (ref) => {
        ref.current.style.zIndex = zIndex;
        setZindex((zIndex) => zIndex + 1);
      };
    
      return (
        <div>
          <Header />
          {notes.map((noteItem) => (
            <Note
              stackNote={stackNote}
              key={noteItem.key}
              title={noteItem.title}
              content={noteItem.content}
            />
          ))}
          <Footer />
        </div>
      );
    }
    

    然后,在Note 组件中,只需在您的handleOnClick 中使用noteRef 调用stackNote

    function handleOnClick(e) {
        e.preventDefault();
        props.stackNote(noteRef);
        offsetX = e.pageX - notePos.x;
        offsetY = e.pageY - notePos.y;
    
        console.log("Mouse is clicked!");
        document.addEventListener("mousemove", handleOnMove);
        document.addEventListener("mouseup", handleOnUp);
      }
    

    别忘了应该删除以前的代码,比如noteRef.current.style.zIndex = ...

    虽然ref在原代码中存在,所以我就照着用了,不过好像没必要用。

    【讨论】:

    • 这成功了!谢谢.. 这就是我一直在寻找的,能够将值传递回父组件...很好!
    • @NumpyNoob 我很高兴听到这个消息:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    相关资源
    最近更新 更多