我在父组件中创建了“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