所以基本上我想要达到的是在组件的返回方法中获取div元素的维度。我通过ref参考了这个,我希望用getBoundingClientRect()
得到它的宽度和高度,但是有错误:Uncaught TypeError: Cannot read property 'getBoundingClientRect' of undefined
。我还尝试了offsetWidth
和offsetHeight
。
这是我的代码:
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,
style: this.props.style,
cursorPos: {},
};
},
extend(obj, src) {
Object.keys(src).forEach(function(key) { obj[key] = src[key]; });
return obj;
},
Tooltip() {
var box = this.refs.button.getBoundingClientRect(),
Height = box.clientHeight,
tooltipStyle = {
};
return <div className="tooltip" style={tooltipStyle}>{this.props.tooltip}</div>;
},
showTooltip(){
},
removeTooltip(){
},
render() {
var _props = this.props,
Tooltip = this.Tooltip,
opts,
disabled = false,
rippleOpacity,
outterStyleMy = {
border: "none",
outline: "none",
padding: "8px 10px",
backgroundColor: "red",
borderRadius: 100 + "%",
cursor: "pointer",
},
iconStyleMy = {
fontSize: 12 + "px",
textDecoration: "none",
textAlign: "center",
display: 'flex',
justifyContent: 'center',
alignItems: 'center',
},
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) {
iconStyleMy = this.state.iconStyle;
};
if (this.state.style) {
outterStyleMy = this.state.style;
};
if (_props.href) {
opts.href = _props.href;
};
var buttonStyle = this.extend(outterStyleMy, iconStyleMy);
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>
);
}
});
ReactDOM.render(
<IconButton href="" className="" iconStyle="" style="" iconClassName="face" disabled="" disableTouchRipple="" tooltip="aaaaa" />,
document.getElementById('app')
);
&#13;
所以......我不知道如何做到这一点。
答案 0 :(得分:1)
在呈现DOM节点之前,您无法获得对它的引用。
在this.refs.button.getBoundingClientRect()
生命周期方法中执行componentDidMount
以确保它已呈现,并且您可以获得对它的引用。