【问题标题】:how to add inline style width:calc(100% / var) in reactjs?如何在 reactjs 中添加内联样式宽度:calc(100% / var)?
【发布时间】:2017-11-25 08:49:29
【问题描述】:
 for (let i = 0; i < divCount.length; i++) {
        var radio = divCount[i].getElementsByClassName("radio_count");
        for (var index = 0; index < radio.length; index++) {
            var element: any = radio[index];
            console.log(element);
             var style ="width:calc(100% / " + element + ")";
            element.style = style;
        }

    }
  1. 我想添加内联样式
  2. 将动态值设置为 100% 分割 前任。宽度:clac(100% / var); 我该怎么做?

【问题讨论】:

    标签: html reactjs


    【解决方案1】:

    Template literals 应该会有所帮助。

    <div style={{width: `calc(100% / ${yourVariable})`}}></div>
    

    例如https://jsfiddle.net/69z2wepo/81579/

    【讨论】:

    【解决方案2】:

    @Andrew 写的是正确的,但是这里是非 ES2015/ES6 版本(问题没有具体说明):

    在react组件渲染中,可以使用如下JSX:

    render: function() {
        var dynamicWidth = 'calc(100% / ' + value + ')';
        return (
          <div>
            <div style={{width: dynamicWidth}}></div>
          </div>
        );
    

    基本上,这是如何在字符串被插值的每个渲染上工作的。 @Andrew 向您展示的只是更好的语法,可用于在 ES6 中做同样的事情

    calc(100% / ${value})在概念上等同于'calc(100% / ' + value + ')'

    【讨论】:

      【解决方案3】:
      for (let i = 0; i < divCount.length; i++) {
              var radio = divCount[i].getElementsByClassName("radio_count");
              for (var index = 0; index < radio.length; index++) {
                  var element: any = radio[index];
                  console.log(element);
                  let width = 100 / radio.length;
                  element.style.width=width + "%";
              }
          }
      

      【讨论】:

      • 如果项目真正基于 React.js,最好使用 React 的状态和渲染功能,而不是查询 DOM 并强制改变它。
      • 我正在使用 reactjs 和没有 jquery 的打字稿。
      【解决方案4】:

      1.ReactJS中的组件可以添加内联样式,如下所示:

      render() {
          return (
              <div style={{ color: 'white', backgroundColor: 'red' }}>
                  Div to be styled
              </div>
          )
      }
      

      或者通过将样式对象传递给组件:

      render() {
          const divStyle = {
              color: 'white',
              backgroundColor: 'red'
          };
      
          return (
              <div style={divStyle}>
                  Div to be styled
              </div>
          )
      }
      
      1. 如您所述,为了根据子元素的数量设置动态宽度,我建议使用 CSS。在包装元素上使用display: flex,在内部元素上使用flex-grow: 1

      示例:https://jsfiddle.net/edyjt34r/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-15
        • 1970-01-01
        • 2018-01-02
        • 2016-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-19
        相关资源
        最近更新 更多