gpt4 book ai didi

javascript - 列表不会在带有 onClick 按钮的 React hook 中重新呈现

转载 作者:行者123 更新时间:2023-12-02 23:27:44 25 4
gpt4 key购买 nike

我有一个简单的 ul 列表,它开始为空,当我单击“添加项目”按钮时,它将元素添加到 dom(我可以通过检查看到它),但它只是没有真正在屏幕上呈现 li 项目...

import React, { useState } from 'react'
import Index from './Index.css'

const Animatedlist = (props) => {

const [items, setItems] = useState([])
const [count, setCount] = useState(0);
const listItems = items.map((item) => <li key={item.id}>{item.value}</li>)

const addItem = () => {
console.log('asdasd6')

setItems([
...items,
{
id: items.length,
value: 'New Item'+items.length
}
])

return items

}

return (
<>
<ul>
{/* {items.map(item => { return <li key={item.id}> {item.value} </li> })} */}
{listItems}
</ul>

<button onClick={addItem}>{props.buttonText}</button>



<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}></button>
</>
)

}

export default Animatedlist

最佳答案

代码看起来和工作正常:

const { useState, Fragment } = React;

const Animatedlist = (props) => {

const [items, setItems] = useState([])
const [count, setCount] = useState(0);
const listItems = items.map((item) => <li key={item.id}>{item.value}</li>)

const addItem = () => {
console.log('asdasd6')

setItems([
...items,
{
id: items.length,
value: 'New Item'+items.length
}
])

return items

}

// I've used React.Fragment because the SO compiler doesn't support <>
return (
<Fragment>
<ul>
{/* {items.map(item => { return <li key={item.id}> {item.value} </li> })} */}
{listItems}
</ul>

<button onClick={addItem}>{props.buttonText}</button>



<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}></button>
</Fragment>
)

}

ReactDOM.render(<Animatedlist buttonText="Add item" />, document.getElementById('app'));
<script src="//cdn.jsdelivr.net/npm/react@16.8.6/umd/react.development.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/react-dom@16.8.6/umd/react-dom.development.min.js"></script>

<div id="app"></div>

如果您在浏览器 DOM 检查器中看到元素已添加到 DOM 并且它们不可见,则唯一可能的原因是 CSS。确保<li>使用 display: none; 不会隐藏 s , visibility: hidden; , opacity: 0; , left: -9999px;

关于javascript - 列表不会在带有 onClick 按钮的 React hook 中重新呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56659003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com