这似乎是一个边缘情况问题,但想象一下,如果我已经有了一个[]的JSX.Elements (特别是div),并且已经有了它们的类。
我想动态添加一个className到它,这是可能的吗?我试着forEach它并添加el.props.className="",但它是一个readOnly道具。
let allDivs = graphHeights.map((height) => {
return (
<div style={{ height: height }} className={styles["mini-div"]}></div>
);
});
现在,我希望遍历allDivs的上述[],并向它们添加特定的classNames
发布于 2020-07-20 22:47:05
当您运行代码时,
<div style={{ height: height }} className={styles["mini-div"]}></div>
将返回react元素,而不是组件。类似于react组件的实例。
所以你所拥有的是一个react元素数组。
要向react元素添加道具,您需要使用cloneElement
https://reactjs.org/docs/react-api.html#cloneelement
let allDivsChanged = allDivs.map(element => {
return React.cloneElement(element, { className: "replaceClassName" });
});
https://stackoverflow.com/questions/63004734
复制相似问题