使用React Hooks从子节点关注父节点



我试图在弹出对话框后聚焦父输入框。我试着把父母的拒绝传递给孩子,从孩子身上转移注意力,但很难奏效。

谢谢你的帮助。

代码沙箱:https://codesandbox.io/s/modal-components-react-custom-hooks-forked-iyumhx?file=/src/Modal.js

代码:

const App = () => {
const { isShowing, toggle, setIsShowing } = useModal();
const [input, setInput] = useState("");
const ref = useRef();
useEffect(() => {
if (input != "") setIsShowing(true);
}, [input]);
return (
<div className="App">
<input type="text" ref={ref} onChange={(e) => setInput(e.target.value)} />
<Modal
isShowing={isShowing}
hide={toggle}
forwardRef={ref}
input={input}
/>
</div>
);
};

在Console.log ref上,我可以看到ref被定义,但focus函数不起作用。

const Modal = ({ isShowing, hide, forwardRef, input }) => {
useEffect(() => {
console.log(forwardRef);
forwardRef.current.focus();
}, []);
return (
<>
<M
isOpen={isShowing}
role="dialog"
autoFocus={true}
centered={true}
size="lg"
// query={query}
scrollable={false}
>
From Parent {input}
</M>
</>
);
};

将你的模态useEffect更改为

useEffect(() => {
if (forwardRef.current) {
forwardRef.current.focus();
}
}, [forwardRef]);

将自动聚焦设置为false。这将防止模态从输入中窃取焦点。

问题是reactstrap库中的模式默认为autoFocus={true},您必须将其设置为false,您也不需要useRef的帮助。下面是工作代码:

App.jsx

import React, { useState } from "react";
import ReactDOM from "react-dom";
import Modal from "./Modal";
import "./styles.css";
import { useBoolean } from "./useBoolean";
const App = () => {
const [isModalOpen, openModal, closeModal] = useBoolean();
const [inputValue, setInputValue] = useState("");
return (
<div className="App">
<input
type="text"
value={inputValue}
onChange={(e) => {
if (e.target.value !== "") openModal();
else closeModal();
setInputValue(e.target.value);
}}
/>
<Modal isOpen={isModalOpen} inputValue={inputValue} />
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Modal.jsx

import React from "react";
import { Modal as M } from "reactstrap";
const Modal = ({ isOpen, inputValue }) => {
return (
<M
isOpen={isOpen}
autoFocus={false} // THIS PART WAS THE ISSUE, THIS SHOULD BE FALSE!
centered={true}
size="lg"
scrollable={false}
>
Input: {inputValue}
</M>
);
};
export default Modal;

useBoolean.js

import { useCallback, useState } from "react";
export const useBoolean = () => {
const [value, setValue] = useState(false);
const onToggleOn = useCallback(() => setValue(true), []);
const onToggleOff = useCallback(() => setValue(false), []);
return [value, onToggleOn, onToggleOff];
};

相关内容

  • 没有找到相关文章

最新更新