限制每行的按钮数量

Limit number of buttons per row

我有 6 个按钮要在我的网页上呈现。

我正在通过 map()

映射 JSON 文件中的数组对象
template(x) {
    return (
        <div>
            <Button bsStyle="primary"></Button>
        </div>
    )
}

render() {
    return (
        <div className="row">
            {_(this.props.data).map((x) => this.template(x))}
        </div>
    )
}

我如何才能将每一行限制为只有 3 个按钮,而不是在被迫转到下一行之前需要多少个按钮?我想将 JSON 文件中的对象数组拆分为两个单独的对象数组,这样我就可以进行两次 map() 调用?似乎有更好更简单的解决方案。

将整个数组分成块(较小的数组,每个数组仅包含 3 个元素)并将这些数组推入 arrayOfChunks(数组的数组),然后在渲染函数中:

{arrayOfChunks.map(this.templateChunk)}

和方法:

templateChunk(chunk) {
    return (<div className="row">
            chunk.map(this.template)
    </div>)
}

我的 React 知识有限,所以我的语法可能不对,但这在渲染函数中的作用是 return 一个行 div 数组,每个行包含 3 个按钮。我认为一个更简单的解决方案是将 flex-box 与您的 css 一起使用,这将允许您指定行中需要多少个元素。

render() {
  return this.props.data.reduce((prev, curr, ind, arr) => {
    if (ind + 1 % 3 === 0) {
      prev.push(createRow(arr.splice(ind - 2, ind + 1)));
    }
    return prev;
  }, [])
}

createRow(arr) {
   return (
        <div className="row">
            {arr.map((x) => this.template(x))}
        </div>
    )
}

template(x) {
    return (
        <div>
            <Button bsStyle="primary"></Button>
        </div>
    )
}