Reactjs React获取组件外部元素的偏移量
我试图获取React组件外部元素的offsetTop、offsetLeft、OffsetLight等,并将值作为内联CSS传递给React组件Reactjs React获取组件外部元素的偏移量,reactjs,Reactjs,我试图获取React组件外部元素的offsetTop、offsetLeft、OffsetLight等,并将值作为内联CSS传递给React组件 class MyComponent extends React.Component { constructor(props) { super(props); } const top = document.getElementById("div1").offsetTop; const left = document.getElem
class MyComponent extends React.Component {
constructor(props) {
super(props);
}
const top = document.getElementById("div1").offsetTop;
const left = document.getElementById("div1").offsetLeft;
const bottom = document.getElementById("div1").offsetHeight;
render() {
return (
<div
className="example"
style={
top: top,
left: left,
bottom: bottom,
};
></div>
);
}
}
类MyComponent扩展了React.Component{
建造师(道具){
超级(道具);
}
const top=document.getElementById(“div1”).offsetTop;
const left=document.getElementById(“div1”).offsetLeft;
const bottom=document.getElementById(“div1”).offsetHeight;
render(){
返回(
);
}
}
上面的代码给出了
顶部
、左侧
和底部
偏移值的未定义
它们未定义,因为看起来您希望将顶部
、左侧
和底部
作为类属性
将它们放在构造函数中:
constructor(props) {
super(props);
this.top = document.getElementById("div1").offsetTop;
this.left = document.getElementById("div1").offsetLeft;
this.bottom = document.getElementById("div1").offsetHeight;
}
使用
{this.top}
,{this.left}
等访问它们。确认外部元素已装入
class MyComponent extends React.Component {
state = { top: 0, left: 0, bottom: 0 }
componentDidMount() {
const top = document.getElementById( "div1" ).offsetTop;
const left = document.getElementById( "div1" ).offsetLeft;
const bottom = document.getElementById( "div1" ).offsetHeight;
this.setState( { top, left, bottom } )
}
render() {
const { top, left, bottom } = this.state;
return (
<div
className="example"
style={
top: top,
left: left,
bottom: bottom,
}
></div>
);
}
}
类MyComponent扩展了React.Component{
状态={top:0,left:0,bottom:0}
componentDidMount(){
const top=document.getElementById(“div1”).offsetTop;
const left=document.getElementById(“div1”).offsetLeft;
const bottom=document.getElementById(“div1”).offsetHeight;
this.setState({top,left,bottom})
}
render(){
const{top,left,bottom}=this.state;
返回(
);
}
}
您是否尝试top:{this.top}?您的意思是问题发生在变量分配阶段?如果是这样,我能想到的唯一原因是没有id为“div1”的元素,因为我无法复制它