gpt4 book ai didi

javascript - react 上下文菜单并观察 Prop 变化

转载 作者:行者123 更新时间:2023-12-02 21:25:44 24 4
gpt4 key购买 nike

大家好,我正在尝试构建 React 上下文菜单组件,这是我的代码当前的样子:

import { css } from '@emotion/core';
import React, { useRef, useEffect, useState } from 'react';


const styles = {
root: css({
position: "fixed",
padding: "5px 10px",
background: "white",
zIndex: 999,
outline: "none",
boxShadow: "0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24)",
}),
};


export default function ContextMenu(props) {

let event = props.show;

const [count, setCount] = useState(0);

const contextEl = useRef();



const handleBlur = () => {
}

if(event) {
return (
<div tabIndex="0" css={styles.root} ref={contextEl} className="context-menu" onBlur={handleBlur}>
{props.children}
</div>
);
}
return null;

这是外部组件的样子:

import React, { useState, useEffect } from 'react';
import * as ReactDOM from 'react-dom';

import ContextMenu from '../components/ContextMenu';

function Home(props) {

const [count, setCount] = useState(false);

// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
document.addEventListener('contextmenu',onClickfn);
});

const onClickfn = (e) => {
e.preventDefault();
setCount(e);
}

return (
<div >
<h1>Hello, world!</h1>
<button>Click me</button>
<ContextMenu show={count}>
asdasdasdasd
</ContextMenu>
</div>
);
}

我试图实现的是将事件传递给内部组件以聚焦元素,然后设置上下文菜单可见的状态,并且当用户单击外部时(模糊事件将处于事件状态,我应该隐藏上下文菜单),然后当用户再次单击时单击外部组件我想检测更改我再次显示组件

有什么办法可以在 React 中实现类似的效果吗?

最佳答案

我想你可以看看this实现:

import { MENU_SHOW, MENU_HIDE } from './actions';
import { uniqueId, hasOwnProp, canUseDOM } from './helpers';

class GlobalEventListener {
constructor() {
this.callbacks = {};

if (canUseDOM) {
window.addEventListener(MENU_SHOW, this.handleShowEvent);
window.addEventListener(MENU_HIDE, this.handleHideEvent);
}
}

handleShowEvent = (event) => {
for (const id in this.callbacks) {
if (hasOwnProp(this.callbacks, id)) this.callbacks[id].show(event);
}
}

handleHideEvent = (event) => {
for (const id in this.callbacks) {
if (hasOwnProp(this.callbacks, id)) this.callbacks[id].hide(event);
}
}

register = (showCallback, hideCallback) => {
const id = uniqueId();

this.callbacks[id] = {
show: showCallback,
hide: hideCallback
};

return id;
}

unregister = (id) => {
if (id && this.callbacks[id]) {
delete this.callbacks[id];
}
}
}

export default new GlobalEventListener();

关于javascript - react 上下文菜单并观察 Prop 变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60746459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com