繁体   English   中英

Reactjs - 正确设置内联样式

[英]Reactjs - setting inline styles correctly

我正在尝试将 Reactjs 与剑道分离器一起使用。 拆分器具有样式属性,例如

style="height: 100%"

使用 Reactjs,如果我理解正确的话,这可以使用内联样式来实现

var style = {
  height: 100
}

但是,我也在使用 Dustin Getz jsxutil来尝试将事物进一步拆分并拥有独立的 html 片段。 到目前为止,我有以下 html 片段(splitter.html)

<div id="splitter" className="k-content">
  <div id="vertical">
    <div>
      <p>Outer splitter : top pane (resizable and collapsible)</p>
    </div>
    <div id="middlePane">
      {height}
      <div id="horizontal" style={height}>
        <div>
          <p>Inner splitter :: left pane</p>
        </div>
        <div>
          <p>Inner splitter :: center pane</p>
        </div>
        <div>
          <p>Inner splitter :: right pane</p>
        </div>
      </div>
    </div>
  <div>
  <p>Outer splitter : bottom pane (non-resizable, non-collapsible)</p>
</div>

和一个 splitter.js 组件,它引用了这个 html,如下所示

define(['react', 'external/react/js/jsxutil','text!internal/html/splitter.html'],
  function(React, jsxutil, splitterHtml) {
    'use strict';
    console.log('in app:' + splitterHtml);
    return React.createClass({

      render: function () {
        var scope = {
          height: 100
        };
        console.log('about to render:' + scope.height);

        var dom = jsxutil.exec(splitterHtml, scope);
        console.log('rendered:' + dom);
        return dom;
      }    
    });
  }
)

现在当我运行它时,如果我把它作为内容,我可以正确地看到高度。 但是,当它作为样式属性执行时,出现错误

The `style` prop expects a mapping from style properties to values, not a string. 

所以我显然还没有完全正确地映射它。

如果有人可以指导我纠正这个问题,我将不胜感激。

您也可以尝试在不使用变量的情况下设置内联style ,如下所示:

style={{"height" : "100%"}}或者,

对于多个属性: style={{"height" : "100%", "width" : "50%"}}

你需要这样做:

var scope = {
     splitterStyle: {
         height: 100
     }
};

然后将此样式应用于所需的元素:

<div id="horizontal" style={splitterStyle}>

在您的代码中,您正在执行此操作(这是不正确的):

<div id="horizontal" style={height}>

其中height = 100

文档中无法立即看出为什么以下内容不起作用:

<span style={font-size: 1.7} class="glyphicon glyphicon-remove-sign"></span>

但是当完全内联时:

  • 你需要双花括号
  • 你不需要把你的价值观放在引号里
  • 如果你省略"em" ,React 会添加一些默认值
  • 记住在 CSS 中有破折号的 camelCase 样式名称 - 例如 font-size 变为 fontSize:
  • class是类className

正确的方法如下所示:

<span style={{fontSize: 1.7 + "em"}} className="glyphicon glyphicon-remove-sign"></span>

正确和更清晰的方法是:

<div style={{"font-size" : "10px", "height" : "100px", "width" : "100%"}}> 
    My inline Style
</div>

通过以下方法使其更简单:

// JS

const styleObject = {
      "font-size" : "10px",
      "height" : "100px",
      "width" : "100%"
}

// HTML

<div style={styleObject}> My inline Style </div>

内联style属性需要对象。 因此它是用{}编写的,它变成了双{{}} ,因为它是用于默认反应标准的。

暂无
暂无

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

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