【发布时间】:2022-01-10 15:16:14
【问题描述】:
如何在 useRef 对象(引用 DOM 元素)中添加组件?
const Red = () => {
return <div className="color">Red</div>;
};
const Black = () => {
return <div className="color">Black</div>;
};
const Green = () => {
return <div className="color">Green</div>;
};
const Button = (params) => {
const clickHandler = () => {
let boolA = Math.random() > 0.5;
if (boolA) {
params.containerRef.current.appendChild(<Red />);
} else {
let boolB = Math.random() > 0.5;
if (boolB) {
params.containerRef.current.appendChild(<Black />);
} else {
params.containerRef.current.appendChild(<Green />);
}
}
};
return <button onClick={clickHandler}>Click</button>;
};
export default function App() {
const containerRef = useRef(null);
return (
<div className="App">
<Button containerRef={containerRef} />
<div ref={containerRef} className="color-container">
Color components should be placed here !
</div>
</div>
);
}
params.containerRef.current.appendChild(); -> 抛出错误。我已经用它来表明我想要发生的事情。
我也在做一个反模式/愚蠢的事情吗?是否有另一种(更智能)的方式来实现上述目标?
编辑: 我忘记添加一些重要信息。 只有 Button 知道并可以决定要添加什么组件。
【问题讨论】:
-
你不能使用 appendChild 并传递一个 react 组件。
-
我把代码留在那里是为了展示我想要完成的事情。
标签: reactjs react-hooks use-ref