**在MouseEnter事件中尝试更改父组件样式时出现react错误。如何通过子组件按钮更改样式?错误为-未捕获错误:重新呈现太多。React限制了呈现的次数以防止无限循环。这似乎很奇怪,因为onMouseLeave={()=〉setHovered(false)}是一个箭头函数。
https://codesandbox.io/s/trusting-moon-djocul?**
// App js
import React, { useState, useEffect } from "react";
import Categories from "./Categories";
import ShopPage from "./components/Products";
export default function App() {
const [data, setData] = useState(Categories);
useEffect(() => {
setData(data);
}, []);
return (
<div className="wrapper">
<ShopPage products={data} filterResult={filterResult} />
</div>
);
}
// Shopping page
const ShopPage = ({ products }) => {
return (
<>
<div>
<Products products={products} />
</div>
</>
);
};
// Parent component, the main part goes here
const Products = ({products}) => {
const [hovered, setHovered] = useState(false);
const [style, setStyle] = useState(false);
if (hovered) {
setStyle({
// inline styles
});
} else {
setStyle({
// inline styles
});
}
return (
<>
<Product setHovered={setHovered} style={style} products={products}/>
</>
);
};
export default Products;
// Child component
const Product = ({ setHovered, style, products }) => {
return (
<div className={styles.items}>
{products.map((value) => {
return (
<>
<div style={style}>
<button
onMouseEnter={() => setHovered(true)}
onMouseLeave={() => setHovered(false)}
>
Add to Cart
</button>
</div>
</>
);
})}
</div>
);
};
export default Product;
1条答案
按热度按时间kgqe7b3p1#
问题是您在组件中设置setHovered状态,简单的解决方案是在useEffect中使用它并添加所需的依赖项。
如果我们讨论一下你的代码,那么你可以通过使用子组件中的状态而不是通过属性来轻松地完成这一点。
我已经更新了你的代码如下:
https://codesandbox.io/s/nameless-cookies-e6pwxn?file=/src/components/Product.js:141-151