仅在组件可以放入Flex容器内时才渲染组件

时间:2017-12-11 16:40:18

标签: css reactjs flexbox

我正在尝试构建一个工具栏,如果没有足够的空间来渲染它们,则会从右侧隐藏组件。我的方法是使用引用,并根据条件添加宽度和渲染,如果总宽度已溢出。我希望得到一些工作,并从那里继续改进它。当屏幕尺寸减小时似乎工作正常,但是当有空间时尝试“重新渲染”组件时则不行。我怀疑添加“无”的显示样式会导致一些问题。

  componentDidMount() {
    this.littleFunction();
    window.addEventListener('resize', this.littleFunction);
  }

  littleFunction = () => {
    let sofar = 0;
    for (const ref in this.refs) {
      sofar += this.refs[ref].offsetWidth;
      const index = ref.indexOf('test');
      console.log(ref, sofar, this.input.offsetWidth);
      if (sofar > this.input.offsetWidth && index === -1) {
        this.refs[ref].style.display = 'none';
      }


      // // console.log(typeof this.refs[ref].style.display, this.refs[ref].style.display);
      // if (this.refs[ref] !== this.input) {
      //   sofar = this.refs[ref].offsetWidth + sofar;
      // }
      // const index = ref.indexOf('test');
      // // console.log(sofar, this.input.offsetWidth, index);
      // if (sofar >= this.input.offsetWidth && index === -1) {
      //   this.refs[ref].style.display = 'none';
      //
      //   this.forceUpdate();
      // } else if (sofar < this.input.offsetWidth && index === -1) {
      //   // console.log('inhiaaa', sofar, this.input.offsetWidth);
      //   this.refs[ref].style.display = '';
      //
      //   this.forceUpdate();
      // }
    }
  }

在考虑了一段时间之后,我意识到如果我将样式设置为显示:'none',下次当我尝试运行此逻辑来检查可以容纳多少组件时,我实际上没有得到长度从之前设置为显示的组件返回:'none'。我所做的是在应用调用函数之前保存组件的宽度。

  componentDidMount() {
    this.widths = new List();
    for (const ref in this.refs) {
      this.widths = this.widths.push(Map({
        name: ref,
        length: this.refs[ref].offsetWidth,
      }));
    }

    this.littleFunction();
    window.addEventListener('resize', this.littleFunction);
  }

  littleFunction = () => {
    let sofar = 0;
    this.widths.forEach(item => {
      sofar += item.get('length');
      const index = item.get('name').indexOf('test');

      if (sofar > this.input.offsetWidth && index === -1) {
        this.refs[item.get('name')].style.display = 'none';
          // this.forceUpdate();
      } else if (index === -1) {
        this.refs[item.get('name')].style.display = 'inline';
          // this.forceUpdate();
      }
    });
  }

1 个答案:

答案 0 :(得分:1)

让工具栏中的样式{ width: '100%', overflow: 'hidden', whiteSpace: 'nowrap' }可以为您提供所需的效果。