【问题标题】:Accessing HTML elements inside a React component访问 React 组件中的 HTML 元素
【发布时间】:2020-02-27 11:33:39
【问题描述】:

我有一个无法编辑的 React 组件 InputComponent,我想获得对其内部 div 之一的引用。 (例如为了专注于输入字段)。

const RefsExamplePage = () => {

    return (
        <div>

            <div>
                <InputComponent
                title="Test component"
                ></InputComponent>
            </div>

        </div>

    )
}

export default RefsExamplePage;

我如何做到这一点?

【问题讨论】:

  • 如果你不能编辑;检查它的孩子是否有一个特定的类名或 id 来选择它们;或者如果没有发现什么特别的东西;用正确的ref 传递给它的子组件,重新实现这个简单的组件
  • 我认为您可能在这里遇到了 X Y 问题。也许与其说您需要对其进行编辑,不如告诉我们您希望在更高级别上实现什么。

标签: reactjs react-ref


【解决方案1】:

我无法编辑

如果你不能编辑它,你唯一能做的就是将ref 传递给它并希望InputComponent 已经实现了引用。

例如

const RefsExamplePage = () => {

    // use inputRef.current to access the input reference
    const inputRef = React.useRef()    

    return (
        <div>

            <div>
                <InputComponent
                    ref={inputRef}
                    title="Test component"
                />
            </div>

        </div>

    )
}

如果这不起作用或给您一些错误,您将需要修改InputComponent

【讨论】:

    【解决方案2】:

    如果InputComponent 不提供ref,您可以包装其父级(div 容器),然后为其设置ref

    import React, { useRef } from "react";
    
    const RefsExamplePage = () => {
        const container = useRef();
        return (
            <div>
    
                <div ref={container}>
                    <InputComponent
                    title="Test component"
                    ></InputComponent>
                </div>
    
            </div>
    
        )
    }
    
    export default RefsExamplePage;
    

    然后就可以通过div的ref访问子元素了。

    【讨论】:

      【解决方案3】:

      使用useRef() 为组件本身创建一个引用。这样就可以获取组件引用,并且可以使用它的.current 属性来获取底层DOM:

      const RefsExamplePage = () => {
      
          const inputRef = useRef();
      
          const getInput = e => {
             // here get the any dom node available
             inputRef.current.querySelector('input').focus();
          };
      
          return (....
                 <InputComponent 
                   ref={inputRef} 
                   onClick={getInput} 
                   title="Test component"/> // <---if no child are passed change to self closing
              ....)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-06
        • 1970-01-01
        • 2019-04-20
        • 1970-01-01
        相关资源
        最近更新 更多