首页 > 解决方案 > Reactjs - 内联样式“顶部”和“左侧”

问题描述

我试图围绕一个更大的圆圈的周边对齐不同的圆圈,为了做到这一点,我必须为每个 div 调整top:left:

我正在尝试通过以下方式内联执行此操作:

for(var i = 0; i < n_circles; i++){

  var posx = divHeigth/2 + Math.round(radius * (Math.cos(theta[i]))) + "px";
  var posy = divHeigth/2 - Math.round(radius * (Math.sin(theta[i]))) + "px";
  console.log("X: " + posx + " Y: " + posy)
  var scope = {
      position: "absolute",
      top: "300px",
      left: {posx},
      backgroundColor: "white"
 }
 var circle = <div className="circles" style={{scope}}></div>
 circles.push(circle)
}

但是,如果我{top}用硬编码文本替换"300px"它就可以了。如您所见,我记录posx并且posy它们的值看起来不错(300px200px。)但是如果我使用变量,它甚至没有在开发人员工具中注册?

如何在 Reactjs 中设置样式top和内联?left

标签: javascriptreactjs

解决方案


for(var i = 0; i < n_circles; i++){

  var posx = divHeigth/2 + Math.round(radius * (Math.cos(theta[i]))) + "px";
  var posy = divHeigth/2 - Math.round(radius * (Math.sin(theta[i]))) + "px";
  console.log("X: " + posx + " Y: " + posy)
  var scope = {
      position: "absolute",
      top: "300px",
      left: {posx}, <---- this is wrong, should simply be "left: posx,"
      backgroundColor: "white"
 }
 var circle = <div className="circles" style={{scope}}></div>
 circles.push(circle)
}

当您将变量应用于代码的 JS 部分(而不是 HTML/JSX)时,您不需要将大括号括起来。


推荐阅读