使用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>
  );
};

儿童组成部分

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无法正常工作。

输入出现时,

自动对焦将获得焦点。

然后,引用将重新聚焦于已将输入放置在地址重新搜索上的地方。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...