问题描述
我在父组件中创建了“ 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>
);
};
儿童组成部分
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
解决方法
我通过使用输入 autoFocus 属性以及 ref 属性来解决该问题。
由于单击按钮后input
出现dynamically
,所以ref.focus
无法正常工作。
自动对焦将获得焦点。
然后,引用将重新聚焦于已将输入放置在地址重新搜索上的地方。