Используя ссылки targetButton, чтобы получить объект 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.info(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 после поиска множества способов ее настройки.





Проблема в этом коде заключается в том, что при использовании styled-components вы должны использовать innerRef вместо ref.