我试图用material-ui和React做一个选择菜单
const SelectLevelButton = forwardRef((props, ref) => {
const [stateLevel, setStateLevel] = useState({
level: "Easy"
});
const [stateMenu, setStateMenu] = useState({
isOpen: false
});
const openMenuHandler = () => {
setStateMenu({
isOpen: true
});
};
const closeMenuHandler = () => {
setStateMenu({
isOpen: false
});
};
const buttonRef = useRef();
console.log(buttonRef.current);
return (
<>
<Menu open={stateMenu.isOpen} anchorEl={buttonRef.current} onClose={closeMenuHandler}>
<MenuItem>Easy</MenuItem>
<MenuItem>Normal</MenuItem>
<MenuItem>Hard</MenuItem>
</Menu>
<div ref={buttonRef}>
<Button onClick={openMenuHandler} color="inherit">{`Level: ${stateLevel.level}`}</Button>
</div>
</>
);
});
export default SelectLevelButton;
但是当我单击按钮以在控制台中打开菜单时,出现此警告:
警告:findDOMNode在StrictMode中已弃用。 findDOMNode传递了StrictMode内部的Transition实例。而是直接将引用添加到要引用的元素。
我该如何解决?
最佳答案
Menu中的anchorEl引用是未定义的,因为您可以从启动时从buttonRef.current获得的未定义获得它。因此,它改用findDOMNode。
打开Menu之前,请参见Material-UI文档。
您需要像这样更改代码(未测试):
const SelectLevelButton = forwardRef((props, ref) => {
const [anchorEl, setAnchorEl] = React.useState(null);
const [stateLevel, setStateLevel] = useState({
level: "Easy"
});
const [stateMenu, setStateMenu] = useState({
isOpen: false
});
const openMenuHandler = event => {
setAnchorEl(event.currentTarget);
setStateMenu({
isOpen: true
});
};
const closeMenuHandler = () => {
setStateMenu({
isOpen: false
});
};
const buttonRef = useRef(); // No need for that
console.log(buttonRef.current);
return (
<>
<Menu open={stateMenu.isOpen} anchorEl={anchorEl} onClose={closeMenuHandler}>
<MenuItem>Easy</MenuItem>
<MenuItem>Normal</MenuItem>
<MenuItem>Hard</MenuItem>
</Menu>
<div ref={buttonRef}>
<Button onClick={openMenuHandler} color="inherit">{`Level: ${stateLevel.level}`}</Button>
</div>
</>
);
});
export default SelectLevelButton;
关于javascript - 警告findDomNode,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60814667/