various changes
This commit is contained in:
@@ -0,0 +1,39 @@
|
||||
import React, { ReactElement, ReactNode } from 'react';
|
||||
|
||||
function renderAttributes(props: Record<string, any>): string {
|
||||
return Object.keys(props)
|
||||
.map((key) => {
|
||||
const value = props[key];
|
||||
if (key === 'children' || value === undefined || value === null) {
|
||||
return '';
|
||||
}
|
||||
return `${key}="${value}"`;
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join(' ');
|
||||
}
|
||||
|
||||
function renderElement(element: ReactNode): string {
|
||||
if (typeof element === 'string' || typeof element === 'number') {
|
||||
return String(element);
|
||||
}
|
||||
|
||||
if (React.isValidElement(element)) {
|
||||
const { type, props } = element;
|
||||
const mapped = React.Children.map(props.children, renderElement)
|
||||
const cilds = mapped? mapped.join('') : props.children;
|
||||
const attributes = renderAttributes(props);
|
||||
return `<${type}${attributes ? ' ' + attributes : ''}>${cilds}</${type}>`;
|
||||
}
|
||||
|
||||
if (Array.isArray(element)) {
|
||||
return element.map(renderElement).join('');
|
||||
}
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
export function jsxToString(element: JSX.Element): string {
|
||||
console.log(element);
|
||||
return renderElement(element);
|
||||
}
|
||||
Reference in New Issue
Block a user