亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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

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

慕哥9229398 2023-12-14 15:12:59
我正在嘗試構建一個下拉菜單?;窘Y構Test是我需要使用 Reactref和styled-components.這是代碼: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 不是工作屬性。當點擊區域之外時,我正在undefined繼續this.refs。發現styled-components有問題,但在 V4 上已解決(我使用的是 V5.1.0)。如何將包裝組件放入我的handleOutsideClick?
查看完整描述

1 回答

?
森林海

TA貢獻2011條經驗 獲得超2個贊

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

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

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

使用React.createRef()
并且您可以使用currentref 變量的屬性來訪問它,如下所示:

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 hookuseRef()

查看完整回答
反對 回復 2023-12-14
  • 1 回答
  • 0 關注
  • 161 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號