我是一名初级前端开发人员。我需要帮助解决这个问题。
我正在尝试将 JSXGraph 与 React+Vite 结合使用。当我将示例代码放在 React 组件上时,SVG 的高度变为不定式。这是代码:
import { JSXGraph } from "jsxgraph";
function JSXBoard () {
const BOARDID = 'board-0';
// input data from LMS
let input = [
2, 4, // point A(x, y)
12, 6, // point B(x, y)
8, 12, // point C(x, y)
2 // unit
];
// JSXGraph board
const board = JXG.JSXGraph.initBoard(BOARDID, {
boundingbox: [0, 15, 15, 0],
axis: true,
showCopyright:true,
showNavigation:true,
});
let A = board.create('point', [input[0], input[1]], {
name: '\\(A\\)',
snapToGrid: true,
label: {offset: [-25, -10], fontSize: 16}
});
let B = board.create('point', [input[2], input[3]], {
name: '\\(B\\)',
snapToGrid: true,
label: {offset: [10, -5], fontSize: 16}
});
let C = board.create('point', [input[4], input[5]], {
name: '\\(C\\)',
snapToGrid: true,
label: {offset: [0, 15], fontSize: 16}
});
let ABC = board.create('polygon', [A, B, C], {
borders: {strokeWidth: 2}
});
return (
<>
</>
)
}
export default JSXBoard;
HTML 代码是:
<div id="board-0-wrapper" className="jxgbox-wrapper">
<div id="board-0" className="jxgbox" data-ar="1 / 1"></div>
</div>
请在https://github.com/ozdilkazim/React-Structural-Engineering-Project找到代码 以及无限高度的部署版本:https://structuralengineering.netlify.app/
我尝试将代码转换为其他组件,但仍然遇到相同的问题
在 HTML 中,它不是
className
,而是 class
。 className
用于组件返回中的实际 JSX——您目前没有 <></>
。这意味着不会应用容器上包含 height
属性的样式。然而,该 HTML 无论如何都不应该真正存在于组件之外,所以让我们暂时搁置它并查看整体方法。
React 组件接触到存在于 React 组件本身之外的 DOM 是很奇怪的。您确实想在 React 组件中渲染包装 HTML,然后将此“JsxGraph”库加载到其中。
这可以通过使用存储
board-0
元素的 HTML 元素引用并将其传递给 initBoard
的 ref 来完成。我们还需要将初始化包装在效果中,以便仅在安装时运行一次,而不是在每次渲染时运行。我们还从解除库绑定的效果中返回一个清理函数。
import React, { useRef, useEffect } from 'react'
import { JSXGraph } from "jsxgraph";
function JSXBoard() {
const boardRef = useRef();
useEffect(() => {
// input data from LMS
let input = [
2,
4, // point A(x, y)
12,
6, // point B(x, y)
8,
12, // point C(x, y)
2, // unit
];
// JSXGraph board
const board = JXG.JSXGraph.initBoard(boardRef.current, {
boundingbox: [0, 15, 15, 0],
axis: true,
showCopyright: true,
showNavigation: true,
});
let A = board.create("point", [input[0], input[1]], {
name: "\\(A\\)",
snapToGrid: true,
label: { offset: [-25, -10], fontSize: 16 },
});
let B = board.create("point", [input[2], input[3]], {
name: "\\(B\\)",
snapToGrid: true,
label: { offset: [10, -5], fontSize: 16 },
});
let C = board.create("point", [input[4], input[5]], {
name: "\\(C\\)",
snapToGrid: true,
label: { offset: [0, 15], fontSize: 16 },
});
let ABC = board.create("polygon", [A, B, C], {
borders: { strokeWidth: 2 },
});
return () => {
JXG.JSXGraph.freeBoard(boardRef.current)
}
}, []);
return (
<div id="board-0-wrapper" className="jxgbox-wrapper">
<div ref={boardRef} id="board-0" className="jxgbox" data-ar="1 / 1"></div>
</div>
);
}
export default JSXBoard;
值得注意的是,存在许多为 React 构建的图形库。
JsxGraph
不是。我不知道这是否适合您,但存在诸如 visx 和 chart.js 之类的东西,仅举几个例子。