Javascript 在两个组件处于同一级别的情况下,如何使用forward ref引用dom节点
当我在textarea组件的textarea上按enter键时,焦点应该在Editor.js组件的textarea中。Javascript 在两个组件处于同一级别的情况下,如何使用forward ref引用dom节点,javascript,reactjs,react-hooks,react-forwardref,Javascript,Reactjs,React Hooks,React Forwardref,当我在textarea组件的textarea上按enter键时,焦点应该在Editor.js组件的textarea中。 这是我的父组件 const Content = () => { return ( <div> <TextArea /> <Editor /> </div> ) } const Content=()=>{
这是我的父组件
const Content = () => {
return (
<div>
<TextArea />
<Editor />
</div>
)
}
const Content=()=>{
返回(
)
}
textarea.js(第一个孩子)
const TextArea=()=>{
功能手柄更改(e){
//如果e.target.value将是enter的值,则将焦点放在Editor.js的textarea上
}
返回(
)
Editor.js
const Editor = () => {
return (
<div>
<textarea/>
</div>
)
const编辑器=()=>{
返回(
)
这就是你的方法:
const TextArea = React.forwardRef((props, ref) => {
const {editorRef} = props;
function handleChange(e) {
//if e.target.value will be that of enter , bring focus to textarea of Editor.js
if(editorRef.current){
editorRef.current.focus();
}
}
return (
<div>
<textarea ref={ref} onChange={handleChange} />
</div>
);
});
const Editor = React.forwardRef((props, ref) => {
return (
<div>
<textarea ref={ref} />
</div>
);
});
const Content = () => {
const textAreaRef = useRef();
const EditorRef = useRef();
return (
<div>
<TextArea ref={textAreaRef} editorRef={EditorRef}/>
<Editor ref={EditorRef} textAreaRef={textAreaRef} />
</div>
);
};
const TextArea=React.forwardRef((道具,ref)=>{
const{editorRef}=props;
功能手柄更改(e){
//如果e.target.value将是enter的值,则将焦点放在Editor.js的textarea上
如果(编辑引用当前){
editorRef.current.focus();
}
}
返回(
);
});
常量编辑器=React.forwardRef((道具,ref)=>{
返回(
);
});
常量内容=()=>{
const textAreaRef=useRef();
const EditorRef=useRef();
返回(
);
};
这是一个可以测试的工作沙盒:我收到了地板错误警告:forwardRef渲染函数只接受两个参数:props和ref。任何附加参数都将未定义。编辑器refs提供了未定义的参数您无法传递第三个参数(它将未定义)在forwardRef上,如文本区域所示,editorRef可以是props的一部分。哎呀,我的错,再试一次,我已经编辑了answer@TaghiKhavari我确实尝试过,但我仍然将editorRef.current设置为未定义。这是我得到的错误警告:无法为函数组件提供引用。尝试访问此引用将失败。是否要使用React.forwardRef()?工作正常。请看我随附的演示
const TextArea = React.forwardRef((props, ref) => {
const {editorRef} = props;
function handleChange(e) {
//if e.target.value will be that of enter , bring focus to textarea of Editor.js
if(editorRef.current){
editorRef.current.focus();
}
}
return (
<div>
<textarea ref={ref} onChange={handleChange} />
</div>
);
});
const Editor = React.forwardRef((props, ref) => {
return (
<div>
<textarea ref={ref} />
</div>
);
});
const Content = () => {
const textAreaRef = useRef();
const EditorRef = useRef();
return (
<div>
<TextArea ref={textAreaRef} editorRef={EditorRef}/>
<Editor ref={EditorRef} textAreaRef={textAreaRef} />
</div>
);
};