簡體   English   中英

如何正確使用 ref 與 React class 組件和樣式組件?

[英]How to properly use ref with a React class component and styled-components?

我正在嘗試構建一個下拉菜單。 基本結構Test是我需要使用 React refstyled-components檢測內容區域外的點擊的地方。

我已經檢查了 SO 中的相關文章,但它們使用了我的 class 組件不支持的鈎子。

這是代碼:

import React from "react";
import PropTypes from "prop-types";
import styled, { ThemeProvider } from "styled-components";

import { theme } from "../theme";

import Icon from "../Icon";

const Container = styled.div`
  display: flex;
`};

const SelectorDiv = styled.div`
  background-color: black;
  color: white;
  height: 100px;
`;

class Test extends React.Component {
  componentDidMount () {
    document.addEventListener("mousedown", this.handleClickOutside);
  }

  componentWillUnmount () {
    document.removeEventListener("mousedown", this.handleClickOutside);
  }

  handleClickOutside = event => {
    console.log(this.refs); // undefined
  }


  handleClickInside = () => {
    alert("Clicked inside");
  }

  render = () => {

    return (
      <ThemeProvider theme={theme}>
        <Container disabled={disabled}>
          <SelectorDiv
            onClick={this.handleClickInside}
            ref={"wrapper"}
          >
            <h1>This is the content to click</h1>
          </SelectorDiv>
        </Container>
      </ThemeProvider>
    );
  };
}
export default Test;

ref 不是工作屬性。 在外部單擊時,我在this.refsundefined 看到styled-components有這個問題,但它在 V4 上得到了解決(我使用的是 V5.1.0)。

如何在我的handleOutsideClick中獲取包裝器組件?

正如您所嘗試的那樣,使用 ref 作為字符串是 React 舊 API 的傳統方式。
他們不建議使用它:

如果您以前使用過 React,您可能熟悉較舊的 API,其中 ref 屬性是一個字符串,例如“textInput”,並且 DOM 節點作為 this.refs.textInput 訪問。 我們建議不要這樣做,因為字符串引用存在一些問題,被認為是遺留問題,並且可能會在未來的某個版本中被刪除。

注意:如果您當前正在使用 this.refs.textInput 訪問 refs,我們建議使用回調模式或 createRef API。

改用React.createRef()
您可以使用 ref 變量的current屬性訪問它,如下所示:




class Test extends React.Component {
  constructor() {
     super(props);
    
     this.selectorRef = React.createRef(null);
  }

  componentDidMount() {
    document.addEventListener("mousedown", this.handleClickOutside);
  }

  componentWillUnmount() {
    document.removeEventListener("mousedown", this.handleClickOutside);
  }

  handleClickOutside = event => {
    console.log(this.selectorRef.current);
  }


  handleClickInside = () => {
    alert("Clicked inside")
  }

  render = () => {

    return (
      <ThemeProvider theme={theme}>
        <Container disabled={disabled}>
          <SelectorDiv
            onClick={this.handleClickInside}
            ref={selectorRef}
          >
            <h1>This is the content to click</h1>
          </SelectorDiv>
        </Container>
      </ThemeProvider>
    );
  };
}
export default Test;

在沙盒上檢查

在功能組件中,您可以使用 React hook useRef()

Refs 和 Dom
使用參考

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM