在每个“X"React 组件之后插入一个元素 [英] Inserting an element after every 'X' React components

查看:20
本文介绍了在每个“X"React 组件之后插入一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 React 组件,它使用 Bootstrap 的 col col-md-4 样式将项目列表呈现为三列.但是,我需要 insert a clearfix div 之后每三个元素以确保下一个行"元素显示在正确的位置.

我当前的渲染代码如下所示:

render() {var resultsRender = $.map(this.state.searchResults, function (item) {return <Item Name={ item.Name } Attributes={ item.Attributes }/>;}返回 (<div>{ resultsRender }</div>);}

Item 简单地渲染一个带有 col 类的 div,包含传入的内容:

render() {返回(

……内容在这里……

);}

我目前的解决方法是将 Item 的索引作为 prop 传入,如果索引是 3 的倍数,然后将 clearfix 类应用到 Item,但这对我来说有点hackish,我更喜欢单独的 div 以允许我只显示所需视口大小的 clearfix(使用 Bootstrap 的 visible-* 类).

我相信一定有比我想出的方法更优雅的方法来解决这个问题.任何建议表示赞赏.

解决方案

您可以迭代数组并每 3 个项目添加一个

:

render() {var items = $.map(this.state.searchResults, function (item) {return <Item Name={ item.Name } Attributes={ item.Attributes }/>;}var resultsRender = [];for (var i = 0; i < items.length; i++) {resultsRender.push(items[i]);如果(我%3 === 2){resultsRender.push(<div className="clearfix"/>);}}返回 (<div>{ resultsRender }</div>);}

I have a React component that renders a list of items into three columns using Bootstrap's col col-md-4 styles. However, I need to insert a clearfix div after every third element to ensure that the next 'row' of elements displays in the correct place.

My current render code looks like this:

render() {
  var resultsRender = $.map(this.state.searchResults, function (item) {
    return <Item Name={ item.Name } Attributes={ item.Attributes } />;
  }

  return (
    <div>{ resultsRender }</div>
  );
}

Item simply renders a div with the col classes, containing the passed-in content:

render() {
  return(
    <div className='col col-md-4'>
      ...content here...
    </div>
  );
}

My current workaround is to pass the index of the Item in as a prop, and then apply the clearfix class to the Item if the index is a multiple of 3, but this feels a bit hackish to me and I would prefer a separate div to allow me to only show the clearfix on the required viewport size (using Bootstrap's visible-* classes).

I'm sure there must be a more elegant way to solve this problem than the one I've come up with. Any suggestions are appreciated.

解决方案

You could iterate your array and add a <div/> every 3 items:

render() {
  var items = $.map(this.state.searchResults, function (item) {
    return <Item Name={ item.Name } Attributes={ item.Attributes } />;
  }

  var resultsRender = [];
  for (var i = 0; i < items.length; i++) {
    resultsRender.push(items[i]);
    if (i % 3 === 2) {
      resultsRender.push(<div className="clearfix" />);
    }
  }

  return (
    <div>{ resultsRender }</div>
  );
}

这篇关于在每个“X"React 组件之后插入一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆