如何使用前向引用引用 dom 节点,其中两个组件处于同一级别
how to reference a dom node using forward ref where the two components are in the same level
当我在 TextArea 组件中的 textarea 上按下 enter 时,焦点应该进入 textarea Editor.js 个分量。
这是我的 parent 组件。
const Content = () => {
return (
<div>
<TextArea />
<Editor />
</div>
)
}
textarea.js(第一个child)
const TextArea = () => {
function handleChange(e){
//if e.target.value will be that of enter , bring focus to textarea of Editor.js
}
return (
<div>
<textarea
onChange={handleChange}
/>
</div>
)
Editor.js
const Editor = () => {
return (
<div>
<textarea/>
</div>
)
这就是您的处理方式:
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>
);
};
这是一个可以测试的工作沙盒:https://codesandbox.io/s/stoic-varahamihira-rp84h?file=/src/App.js
当我在 TextArea 组件中的 textarea 上按下 enter 时,焦点应该进入 textarea Editor.js 个分量。
这是我的 parent 组件。
const Content = () => {
return (
<div>
<TextArea />
<Editor />
</div>
)
}
textarea.js(第一个child)
const TextArea = () => {
function handleChange(e){
//if e.target.value will be that of enter , bring focus to textarea of Editor.js
}
return (
<div>
<textarea
onChange={handleChange}
/>
</div>
)
Editor.js
const Editor = () => {
return (
<div>
<textarea/>
</div>
)
这就是您的处理方式:
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>
);
};
这是一个可以测试的工作沙盒:https://codesandbox.io/s/stoic-varahamihira-rp84h?file=/src/App.js