【问题标题】:The clientWidth property of ref button return undefinedref 按钮的 clientWidth 属性返回 undefined
【发布时间】:2018-07-25 08:43:55
【问题描述】:

使用targetButton refs 获取Button dom,我想在单击此Button 时获取clientWidth 属性。

import React from "react";
import styled from "styled-components";

const Container = styled.div`
  width: 600px;
  height: 600px;
  background-color: black;
`;
const Button = styled.button`
  font-size: 24px;
  padding: 1em 2em;
  margin: 3px;
  border: 0;
  outline: 0;
  color: white;
  background-color: #2196f3;
  border-radius: 0.15em;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.3);
  -webkit-appearance: none;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  -webkit-tap-highlight-color: transparent;
`;

const Ripple = styled.div.attrs({
  size: props => props.size
})`
  width: ${props => props.size};
  height: ${props => props.size};
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.7);
  position: absolute;
`;

class RippleButton extends React.Component {
  state = {
    rippleNum: 0
  };
  addRipple() {
    const { clientWidth, clientHeight } = this.targetButton;
    console.log(clientWidth);
    this.setState({
      rippleNum: this.state.rippleNum + 1
    });
  }
  render() {
    const children = [];
    for (let i = 0; i < this.state.rippleNum; i += 1)
      children.push(
        <Ripple
          size={Math.max(
            this.targetButton.clientWidth,
            this.targetButton.clientHeight
          )}
          key={i}
        />
      );
    return (
      <Container>
        <Button
          ref={elem => {
            this.targetButton = elem;
          }}
          onClick={this.addRipple.bind(this)}
        >
          Button{children}
        </Button>
      </Container>
    );
  }
}

export default RippleButton;

在搜索了许多调整方法后,控制台报告了undefined 错误消息。

【问题讨论】:

    标签: reactjs ref styled-components


    【解决方案1】:

    这段代码的问题是当使用styled-components时,你应该使用innerRef而不是ref

    【讨论】:

      猜你喜欢
      • 2023-03-06
      • 2019-03-13
      • 2015-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多