假设我有一个这样的数组:
const a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17, 18, 19];
我想返回一个包含a的值的react组件,将它们作为10个元素的一组。因此预期的输出将是:
<MyReactBox>
<span>The first ten</span>
<span>0, 1, 2, 3, 4, 5, 6, 7, 8, 9</span>
<span>The last ten</span>
<span>10, 11, 12, 13, 14, 15, 16, 17, 18, 19</span>
</MyReactBox>
最好的方法是什么?
class TodoApp extends React.Component {
constructor(props) {
super(props)
}
render() {
const getCustom = (rangeFirst, rangeLast) => {
return(
<div>
<span>The first ten</span>
<span>{rangeFirst}</span>
<span>The last ten</span>
<span>{rangeLast}</span>
</div>
);};
const a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17, 18, 19];
return (
<div>
<span>{getCustom(a.slice(0,10).join(", "), a.slice(-10).join(", "))}</span>
</div>
)
}
}
ReactDOM.render(<TodoApp />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
这里,替换成你的组件-
<div>
<span>The first ten</span>
<span>{rangeFirst}</span>
<span>The last ten</span>
<span>{rangeLast}</span>
</div>
一种方法是使用slice
和Array.from
方法基于数组大小动态构建。这应该适用于任何大小的数组。(只是标签数组更新自定义标题)
const a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17, 18, 19];
const labels = ['first', 'second', 'third', 'fourth']
const Component = () => {
const len = Math.ceil(a.length / 10);
return (
<div>
{Array.from({ length: len }, (_, idx) => (
<div key={`The ${(idx+1) === len ? 'last' : labels[idx] || idx} Ten : `}>
<span>{`The ${(idx+1) === len ? 'last' : labels[idx]} Ten : `}</span>
<span>{a.slice(idx * 10, idx * 10 + 10).join(', ')}</span>
</div>
))}
</div>
);
};
ReactDOM.render(<Component />, document.getElementById("app"));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="app"></div>
const Component = () => {
const a = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17, 18, 19];
const labels = ['first', 'last'];
const n = 10;
return (
<MyReactBox>
{labels.map((label, index) => {
return (
<>
<span>The {label} ten</span>
<span>
{a.slice(index*n, index*n+n).map((number, numberIndex) => {
if (numberIndex !== 0) return `, ${number}`;
return number;
})}
</span>
</>
)
})}
</MyReactBox>
)
}