使用 useRef 动态关注输入(子组件)不起作用



我在父组件中创建了"textRef",并使用createRef((将其传递给子组件。我正在尝试动态地将子组件中的输入集中在道具更改上。

当我在localhost(chrome(上测试时,它确实有效,但在web视图上不起作用。

关于这个问题有什么建议吗?谢谢

父组件

const UserAddressForm = ({ query }) => {
const textRef = useRef(null);
const {
state: { newAddress },
saveMultiData,
} = query;
useEffect(() => {
if (textRef && textRef.current) {
textRef.current.focus();
}
}, [newAddress.zipcode]);
const onAddressChange = (type, value) => {
const addressObj = {
...newAddress,
};
...
saveMultiData({ newAddress: addressObj });
};
return (
<InfoUl margin="21px 0px 0px;">
...
<TextField
ref={textRef}
label=""
name="addr2"
placeholder="상세주소 입력"
textField={newAddress}
onInputChange={e => onAddressChange('addr2', e.target.value)}
/>

</InfoUl>
);
};

children组件

import React from 'react';
import PropTypes from 'prop-types';
import { LabelBox, InputBox } from './styles';
const TextField = React.forwardRef(
(
{
label = null,
name,
type,
placeholder,
textField,
onInputChange,
autoComplete,
pattern,
disabled,
width,
flex,
marginRight,
marginBottom,
},
ref,
) => (
<LabelBox width={width} marginBottom={marginBottom}>
{label !== null && <label htmlFor={label}>{label}</label>}
<InputBox flex={flex} marginRight={marginRight}>
<input
ref={ref}
type={type || 'text'}
name={name}
placeholder={placeholder}
value={textField[name] || ''}
onChange={onInputChange}
autoComplete={autoComplete || 'on'}
pattern={pattern || null}
disabled={!!disabled}
/>
</InputBox>
</LabelBox>
),
);

版本

React v16.9.0

我通过使用inputautoFocus属性和ref特性来解决它。

由于单击按钮时input显示为dynamically,因此ref.focus不起作用。

当输入出现时,自动对焦将获得焦点。

然后Ref将重新聚焦在地址重新搜索中已放置输入的位置。

最新更新