React:将焦点添加到作为包装器的组件的第一个子级 [英] React: add focus to first child of a component which is a wrapper
问题描述
如果我有一个像
这样的组件const Comp = ({children}) =>{//一些代码返回 (<div>{孩子们}
)}
然后像这样调用
<input onChange={...}/><input onChange={...}/></Comp>
如何在组件呈现时从 Comp
组件内将焦点更改到此组件的第一个输入字段.
理想情况下,我想要一个 useEffect 函数或类似的东西
useEffect(() => {thisComponent.firstChild.focus()})
你需要两个东西,useRef
和 useEffect
,useRef
来获取目标元素 ref 和 useEffect
用于在组件渲染时处理焦点.
children
在组件 props 中是一个数组,所以你可以操作它,你可以使用 index
来获取你想要的 child
元素设置ref,然后通过useEffect
中的ref调用focus()
:
function App(props) {const firstChildRef = useRef(null);useEffect(() => {如果(firstChildRef.current){firstChildRef.current.focus()}}, [firstChildRef])返回 ({props.children.map((child, index) => {如果(索引 === 0){返回 {...child, ref: firstChildRef};}返回孩子;})});}
If I have a component like
const Comp = ({children}) => {
//some code
return (
<div>
{children}
</div>
)
}
and then call it like
<Comp>
<input onChange={...} />
<input onChange={...} />
</Comp>
How can I change the focus to the first input field of this component when the component renders, from within the Comp
component.
Ideally I would like to have a useEffect function or something which looks something like
useEffect(() => {
thisComponent.firstChild.focus()
})
You need two things, useRef
and useEffect
, useRef
for getting target element ref, and useEffect
for handling focusing when then component renders.
children
in a component props is an array, so you can manipulate it, you can use index
to get which child
element you want to set ref, and then call focus()
by ref in useEffect
:
function App(props) {
const firstChildRef = useRef(null);
useEffect(() => {
if(firstChildRef.current) {
firstChildRef.current.focus()
}
}, [firstChildRef])
return (
<div className="App">
{props.children.map((child, index) => {
if(index === 0) {
return {...child, ref: firstChildRef};
}
return child;
})}
</div>
);
}
这篇关于React:将焦点添加到作为包装器的组件的第一个子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!