简体   繁体   English

找不到在运行时更改reactjs元素位置的方法

[英]Can't find a way to change reactjs element position on runtime

I wrote some react.component and i define the position as fixed. 我写了一些react.component并且定义了固定位置。
i need to move this element position on runtime and 我需要在运行时移动此元素位置,

 render(){
    var t = <div className="myElement" />;
    t.top = '${500}px';
    t.left = '${900}px';

     return t;     // the element position need to be now 500, 900 
 }

Seems like you just need to pass some inline css rules: 似乎您只需要通过一些内联CSS规则即可:

render(){
  const s = {top: '500px', left: '900px'};
  return (
    <div className="myElement" style={s} />
  );
}

or, the more compact version: 或者,更紧凑的版本:

render(){
  return (
    <div className="myElement" style={{top: '500px', left: '900px'}} />
  );
}

React will automatically px if a unit is missing. 如果缺少单位,React将自动px So you can also do: {top: 500, left: 900} 因此,您也可以执行以下操作: {top: 500, left: 900}


From the docs : 文档

The style attribute accepts a JavaScript object with camelCased properties rather than a CSS string. 样式属性接受带有camelCased属性的JavaScript对象,而不是CSS字符串。 This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes. 这与DOM样式的JavaScript属性一致,效率更高,并且可以防止XSS安全漏洞。

For this you can try the following method, 为此,您可以尝试以下方法,

render(){
let newStyle={
  top:500,
  left:900,
  position:"fixed",
}

return <div style={newStyle} />
}

Here you can assign any value at runtime for the location of the element during runtime by setting the value at the place of 500 and 900. Thus making the size dynamic. 在此处,可以通过在值500和900处设置值,在运行时为元素的位置分配任何值。这样就可以动态调整大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM