1
所以基本上我想要達到的是獲取組件的返回方法內的div元素的尺寸。我通過ref得到這個參考,我想用getBoundingClientRect()
得到它的寬度和高度,但是有錯誤:Uncaught TypeError: Cannot read property 'getBoundingClientRect' of undefined
。我也試過offsetWidth
和offsetHeight
。Reactjs,如何獲得元素的尺寸
這裏是我的代碼:
import React from 'react';
import ReactDOM from 'react-dom';
import Style from 'style-it';
var Ink = require('react-ink');
import FontIcon from '../FontIcon/FontIcon';
var IconButton = React.createClass({
getInitialState() {
return {
iconStyle: this.props.iconStyle,
\t style: this.props.style,
cursorPos: {},
};
},
extend(obj, src) {
Object.keys(src).forEach(function(key) { obj[key] = src[key]; });
return obj;
},
Tooltip() {
\t var box = this.refs.button.getBoundingClientRect(),
\t Height = box.clientHeight,
\t tooltipStyle = {
\t \t };
\t return <div className="tooltip" style={tooltipStyle}>{this.props.tooltip}</div>;
\t },
\t showTooltip(){
\t },
\t removeTooltip(){
\t },
render() {
var _props = this.props,
Tooltip = this.Tooltip,
\t opts,
disabled = false,
rippleOpacity,
\t outterStyleMy = {
\t border: "none",
\t \t outline: "none",
\t \t padding: "8px 10px",
\t backgroundColor: "red",
\t borderRadius: 100 + "%",
\t cursor: "pointer",
\t },
\t iconStyleMy = {
\t \t fontSize: 12 + "px",
\t \t textDecoration: "none",
\t \t textAlign: "center",
\t \t display: 'flex',
\t \t justifyContent: 'center',
\t \t alignItems: 'center',
\t },
rippleStyle = {
color: "rgba(0,0,0,0.5)",
};
if (_props.disabled || _props.disableTouchRipple) {
rippleStyle.opacity = 0;
};
if (_props.disabled) {
disabled = true;
};
if (this.state.labelStyle) {
\t iconStyleMy = this.state.iconStyle;
};
\t if (this.state.style) {
outterStyleMy = this.state.style;
};
if (_props.href) {
opts.href = _props.href;
};
\t var buttonStyle = this.extend(outterStyleMy, iconStyleMy);
\t return(
<Style>
{`
.IconButton{
position: relative;
}
.IconButton:disabled{
color: ${_props.disabledColor};
}
.btnhref{
text-decoration: none;
}
`}
<a {...opts} className="btnhref" >
<Tooltip />
<button ref="button" className={"IconButton" + _props.className} disabled={disabled} style={buttonStyle}
onMouseEnter={this.showTooltip} onMouseLeave={this.removeTooltip} >
<Ink background={true} style={rippleStyle} opacity={rippleOpacity} />
<FontIcon className={_props.iconClassName}/>
</button>
</a>
</Style>
\t \t);
}
});
ReactDOM.render(
<IconButton href="" className="" iconStyle="" style="" iconClassName="face" disabled="" disableTouchRipple="" tooltip="aaaaa" />,
document.getElementById('app')
);
所以...我不知道如何做到這一點。
非常感謝,它的工作:) – Karol