我不确定执行此操作的最佳方法是什么,但是 - 我已经输出了 div 列表。当我单击其中一个时,它会得到一个 class active
。单击 div 后,我需要在此特定类中显示我制作(渲染)的组件。我正在使用带有 react 的 next.js 并且一直在使用 CSS 模块。
目前我尝试过:ReactDOM.render( <InnerDisc/>, document.getElementsByClassName(styles.active) );
但出现错误Error: Target container is not a DOM element.
子(InnerDisc)组件
const InnerDisc = (props) => {
const active = props.active;
if (active) {
return (
<div className={styles.wrapper}>
<Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
<Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
<Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
<Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
<Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
<Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
<Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
<Image className={styles.pic} src="https://picsum.photos/200/300" width={200} height={200}/>
</div>
);
}
}
导出默认 InnerDisc;
主要应用组件
export default function Home() {
const [discs, setDiscs] = useState([
{ id: 1, top: 100 },
{ id: 2, top: 200 },
{ id: 3, top: 300 },
{ id: 4, top: 400 },
{ id: 5, top: 500 },
{ id: 6, top: 600 },
{ id: 7, top: 700 },
{ id: 8, top: 800 },
{ id: 9, top: 900 },
{ id: 10, top: 1000 },
{ id: 11, top: 1100 },
{ id: 12, top: 1200 }
])
function enlargeDisc(e, num) {
let t = e.target
if (t.classList.contains(styles.active)) {
t.classList.remove(styles.active)
discRender()
} else {
t.classList.add(styles.active)
discRender()
}
}
function discRender() {
ReactDOM.render(
<InnerDisc/>, document.getElementsByClassName(styles.active)
);
}
return (
<div className={styles.container}>
<div className={styles.wrapper}>
{discs.map((item) => (
<div className ={styles.disc} key={item.id} style=.
{{top: item.top + 'px'}} onClick={(e)=>
enlargeDisc(e, item.id)}> </div>
))}
</div>
</div>
</div>
)
}