我正试图通过setState((的更改来在JSX中呈现一个10 x 10的复选框输入表单,因为我想让用户能够更改维度的数量来呈现20x20或15x15之类的内容。我尝试过映射(items=>{}(,但它不起作用。
const [xCells, setXCells] = useState(10)
const [yCells, setYCells] = useState(10)
let arrX = Array.apply(null, { length: xCells }).map(Number.call, Number)
let arrY = Array.apply(null, { length: yCells }).map(Number.call, Number)
return (
<div className="RestaurantSeating">
{' '}
{arrX.map(item => {
arr.map(item => {
return <input type="checkbox" />
})
})}{' '}
</div>
)
主要问题是您在映射函数{}
中使用大括号,这意味着您应该显式写入返回值,即return arrY.map...
,目前您没有返回任何值(undefined
(。或者,您可以省略大括号以隐式返回yCells映射:
function MyComponent() {
const [xCells, setXCells] = React.useState(10)
const [yCells, setYCells] = React.useState(10)
let arrX = Array.apply(null, { length: xCells }).map(Number.call, Number)
let arrY = Array.apply(null, { length: yCells }).map(Number.call, Number)
return (
<div className="RestaurantSeating">
{arrX.map(x =>
<div key={x} className="row">
{arrY.map(y =>
<input key={y} type="checkbox" />
)}
</div>
)}
</div>
)
}
ReactDOM.render(<MyComponent />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
这方面的替代方案是:
{new Array(xCells).fill(0).map(_ => {
return (<div>
{new Array(yCells).fill(0).map(_ => {
return <input type="checkbox" />
})}
</div>)
})}
function Test(){
const [xCells, setXCells] = React.useState(10);
const [yCells, setYCells] = React.useState(10);
return (
<div className="RestaurantSeating">
{' '}
{new Array(xCells).fill(0).map(_ => {
return (<div>
{new Array(yCells).fill(0).map(_ => {
return <input type="checkbox" />
})}
</div>)
})}{' '}
</div>
)
}
ReactDOM.render(<Test />, document.querySelector("#app"))
<script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<div id="app"></div>