【发布时间】:2023-01-19 15:57:54
【问题描述】:
试图在不触及第三方包的情况下将我的反应元素附加到第三方呈现的组件(DOM 元素)中。
SomeComponent 在内部定义和呈现tools 数据,它不提供 API 来自定义或扩展 tools。所以我想通过 DOM 操作直接扩展 tools 视图。
third-party.tsx:
import * as React from 'react';
export const SomeComponent = () => {
const tools = [
{ value: 1, action: () => console.log('a') },
{ value: 2, action: () => console.log('b') },
{ value: 3, action: () => console.log('c') },
];
return (
<div>
<ul className="tools-wrapper">
{tools.map((tool) => (
<li onClick={tool.action} key={tool.value}>
{tool.value}
</li>
))}
</ul>
</div>
);
};
App.tsx:
import * as React from 'react';
import './style.css';
import { SomeComponent } from './third-party';
export default function App() {
const customTools = [
{ value: 100, action: () => console.log('hello') },
{ value: 100, action: () => console.log('world') },
];
const customToolElements = (
<React.Fragment>
{customTools.map((tool) => (
<li key={tool.value} onClick={tool.action}>
{tool.value}
</li>
))}
</React.Fragment>
);
React.useEffect(() => {
const toolsWrapper = document.querySelector('.tools-wrapper');
// Append react elements into third-party rendered DOM element.
// Of course, it throws an error, customToolElements is not a DOM native Node type.
toolsWrapper.appendChild(customToolElements);
}, []);
return (
<div>
<SomeComponent />
</div>
);
}
是否可以直接通过 DOM 操作而不是数据驱动的 API 来扩展第三方组件?
【问题讨论】: