Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(react): 支持在React中调用update #1

Merged
merged 1 commit into from
Nov 15, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"site:intranet": "cd site && vite build --mode intranet",
"site:preview": "cd site && vite build --mode preview && cd ../_site && cp index.html 404.html",
"prebuild": "rimraf es/* lib/* dist/* esm/*",
"build": "cross-env NODE_ENV=production rollup -c script/rollup.config.js",
"build": "npm run generate:entry && cross-env NODE_ENV=production rollup -c script/rollup.config.js",
"build:tsc": "run-p build:tsc-*",
"build:tsc-lib": "tsc --emitDeclarationOnly -d -p ./tsconfig.build.json --outDir lib/",
"build:tsc-esm": "tsc --emitDeclarationOnly -d -p ./tsconfig.build.json --outDir esm/",
Expand Down Expand Up @@ -71,7 +71,7 @@
"lodash": "~4.17.15",
"omi-transition": "^0.1.11",
"tailwind-merge": "^2.2.1",
"tdesign-icons-web-components": "^0.1.5"
"tdesign-icons-web-components": "^0.2.0"
},
"devDependencies": {
"@babel/core": "^7.24.7",
Expand Down
2 changes: 1 addition & 1 deletion script/generate-entry.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const components = fs.readdirSync(componentsPath).filter((name) => {
return false;
});

const code = components.reduce((pre, next) => `${pre}export * from './${next}';\n`, '');
const code = components.reduce((pre, next) => `${pre}export * from './${next.replace(/\.ts/, '')}';\n`, '');

fs.writeFileSync(path.resolve(componentsPath, 'index.ts'), code, {
encoding: 'utf-8',
Expand Down
17 changes: 13 additions & 4 deletions site/docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,22 +69,31 @@ export default defineConfig({

```javascript
import { renderReact } from 'tdesign-web-components';
import type { ExtendedElement } from 'tdesign-web-components';
```

在React项目中使用

```javascript
const App: React.FC = () => {
const ref = React.useRef<HTMLDivElement>(null);
const tdComponent = React.useRef<ExtendedElement>();

const changeTheme = () => {
if(!tdComponent.current) return;
tdComponent.current.props.theme = 'danger';
tdComponent.current.update(); // 调用update更新对应的组件
}

React.useEffect(() => {
if (ref.current) {
renderReact(<t-button>BUTTON</t-button>, ref.current)
}
tdComponent.current = renderReact(<t-button theme={'primary'}>BUTTON</t-button>, ref.current);
}, [])


return (
<div ref={ref}></div>
<div ref={ref}>
<button onClick={changeTheme}>点击我切换主题</button>
</div>
)
}
```
Expand Down
102 changes: 0 additions & 102 deletions site/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,108 +13,6 @@
</head>
<body>
<div id="app"></div>
<script>
// 主题方案采用css变量,此处先注释
// document.addEventListener('DOMContentLoaded', function () {
// try {
// if (
// localStorage.theme === "dark" ||
// (!("theme" in localStorage) &&
// window.matchMedia("(prefers-color-scheme: dark)").matches)
// ) {
// walkDOMAndToggleDark(document.body, false)
// document.documentElement.classList.add("dark");
// } else {
// walkDOMAndToggleDark(document.body, true)
// document.documentElement.classList.remove("dark");
// }
// } catch (_) { }
// })


// function toggleNodeDark(node, isDark) {
// if (
// node instanceof HTMLElement &&
// node.tagName.toLowerCase().indexOf("-") !== -1
// ) {
// if (isDark) {
// node.classList.remove("dark");
// } else {
// node.classList.add("dark");
// }

// }
// }

// function walkDOMAndToggleDark(rootNode, isDark) {
// if (isDark) {
// document.documentElement.classList.remove("dark");
// } else {
// document.documentElement.classList.add("dark");
// }
// const treeWalker = document.createTreeWalker(
// rootNode,
// NodeFilter.SHOW_ELEMENT,
// null,
// false
// );

// while (treeWalker.nextNode()) {
// const node = treeWalker.currentNode;
// toggleNodeDark(node, isDark);

// // Check if the node has a shadow root
// if (node.shadowRoot) {
// walkDOMAndToggleDark(node.shadowRoot, isDark);
// }

// // Check if the node has assigned nodes (for slots)
// if (node.assignedNodes) {
// node.assignedNodes().forEach((assignedNode) => {
// if (assignedNode.nodeType === Node.ELEMENT_NODE) {
// walkDOMAndToggleDark(assignedNode, isDark);
// }
// });
// }
// }
// }

// function toggleDark() {
// if (document.documentElement.classList.contains("dark")) {
// localStorage.theme = "light";
// walkDOMAndToggleDark(document.body, true)
// document.documentElement.classList.remove("dark");
// } else {
// localStorage.theme = "dark";
// walkDOMAndToggleDark(document.body, false)
// document.documentElement.classList.add("dark");
// }
// }

// function setDarkMode() {
// localStorage.theme = "dark";
// walkDOMAndToggleDark(document.body, false)
// document.documentElement.classList.add("dark");
// }

// function setLightMode() {
// localStorage.theme = "light";
// walkDOMAndToggleDark(document.body, true)
// document.documentElement.classList.remove("dark");
// }

// function refreshDark() {
// if (document.documentElement.classList.contains("dark")) {
// walkDOMAndToggleDark(document.body, false)
// } else {
// walkDOMAndToggleDark(document.body, true)
// }
// }

// window.addEventListener('load', function() {
// refreshDark()
// })
</script>
<script type="module" src="/main.tsx"></script>
</body>
</html>
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export * from './popup';
export * from './progress';
export * from './radio';
export * from './range-input';
export * from './react.ts';
export * from './react';
export * from './select';
export * from './select-input';
export * from './skeleton';
Expand Down
25 changes: 22 additions & 3 deletions src/react.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,27 @@
* 在React环境中使用的兼容方法
*/

import { render } from 'omi';
import { Component, render } from 'omi';

export type ExtendedElement = (HTMLElement | SVGAElement | HTMLInputElement) & {
receiveProps: Function;
update: Function;
queuedUpdate: Function;
store?: unknown;
className?: string;
props: Record<string, unknown>;
splitText?: Function;
prevProps?: Record<string, unknown> & {
ref?:
| {
current?: unknown;
}
| Function;
};
attributes: NamedNodeMap;
_component?: Component;
_listeners: Record<string, Function>;
} & Record<string, unknown>;

const convertReactToOmi = (r: any): Omi.ComponentChild => {
if (!r) return r;
Expand Down Expand Up @@ -49,8 +69,7 @@ const convertReactToOmi = (r: any): Omi.ComponentChild => {
* @param reactVNode react的vnode结构
* @param root 需要挂载的html
*/
const renderReact = <T = any>(reactVNode: T, root: HTMLElement) => {
const renderReact = <T = any>(reactVNode: T, root: HTMLElement): ExtendedElement =>
render(convertReactToOmi(reactVNode), root);
};

export { renderReact, convertReactToOmi };
Loading