- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 React 应用程序中使用 MathJax。 MathJax 带来了很大的复杂性:它有自己的并发管理系统,并对 DOM 进行了 React 不知道的更改。这导致了很多 DOM 微观管理,这些管理通常被认为是 React 中的反模式,我想知道我的代码是否可以做得更好。
在下面的代码中,MJX
是一个以 TeX 字符串作为输入并将其输入 MathJax 的组件。 RenderGroup
是一个方便的组件,可以跟踪其所有 MJX
的时间。后代已经排版完毕。
/// <reference types="mathjax" />
import * as React from "react";
/* Promise that resolves once MathJax is loaded and ready to go */
export const MathJaxReady = new Promise<typeof MathJax>((resolve, reject) => {
const script = $("#js-async-mathjax");
if (!script) return;
if (window.hasOwnProperty("MathJax")) {
MathJax.Hub.Register.StartupHook("End", resolve);
} else {
script.addEventListener("load", () => MathJax.Hub.Register.StartupHook("End", resolve));
}
});
interface Props extends React.HTMLAttributes<HTMLSpanElement> {
display?: boolean;
}
export class MJX extends React.Component<Props, {}> {
private resolveReady: () => void;
domElement: HTMLSpanElement;
jax: MathJax.ElementJax;
// Promise that resolves after initial typeset
ready: Promise<void>;
static defaultProps = {
display: false
}
constructor(props: Props) {
super(props);
this.ready = new Promise((resolve, reject) => this.resolveReady = resolve);
this.Typeset = this.Typeset.bind(this);
}
async componentDidMount() {
await MathJaxReady;
this.Typeset()
.then(() => this.jax = MathJax.Hub.getAllJax(this.domElement)[0])
.then(this.resolveReady);
}
shouldComponentUpdate(nextProps, nextState) {
/* original span has been eaten by MathJax, manage updates ourselves */
const text = this.props.children instanceof Array ? this.props.children.join("") : this.props.children,
nextText = nextProps.children instanceof Array ? nextProps.children.join("") : nextProps.children;
// rerender?
if (this.jax && text !== nextText) {
this.jax.Text(nextProps.children);
}
// classes changed?
if (this.props.className !== nextProps.className) {
const classes = this.props.className ? this.props.className.split(" ") : [],
newClasses = nextProps.className ? nextProps.className.split(" ") : [];
const add = newClasses.filter(_ => !classes.includes(_)),
remove = classes.filter(_ => !newClasses.includes(_));
for (const _ of remove)
this.domElement.classList.remove(_);
for (const _ of add)
this.domElement.classList.add(_);
}
// style attribute changed?
if (JSON.stringify(this.props.style) !== JSON.stringify(nextProps.style)) {
Object.keys(this.props.style || {})
.filter(_ => !(nextProps.style || {}).hasOwnProperty(_))
.forEach(_ => this.props.style[_] = null);
Object.assign(this.domElement.style, nextProps.style);
}
return false;
}
Typeset(): Promise<void> {
return new Promise((resolve, reject) => {
MathJax.Hub.Queue(["Typeset", MathJax.Hub, this.domElement]);
MathJax.Hub.Queue(resolve);
});
}
render() {
const {children, display, ...attrs} = this.props;
const [open, close] = display ? ["\\[", "\\]"] : ["\\(", "\\)"];
return (
<span {...attrs} ref={node => this.domElement = node}>{open + children + close}</span>
);
}
}
// wait for a whole bunch of things to be rendered
export class RenderGroup extends React.Component {
private promises: Promise<void>[];
ready: Promise<void>;
componentDidMount() {
this.ready = Promise.all(this.promises).then(() => {});
}
render() {
this.promises = [];
return recursiveMap(this.props.children, node => {
if (typeof node.type === "function" && node.type.prototype instanceof MJX) {
const originalRef = node.ref;
return React.cloneElement(node, {
ref: (ref: MJX) => {
if (!ref) return;
this.promises.push(ref.ready);
if (typeof originalRef === "function") {
originalRef(ref);
} else if (originalRef && typeof originalRef === "object") {
originalRef.current = ref;
}
}
});
}
return node;
});
}
}
// recursive React.Children.map
export function recursiveMap(
children: React.ReactNode,
fn: (child: React.ReactElement<any>) => React.ReactElement<any>
) {
return React.Children.map(children, (child) => {
if (!React.isValidElement<any>(child)) {
return child;
}
if ("children" in child.props) {
child = React.cloneElement(child, {
children: recursiveMap(child.props.children, fn)
});
}
return fn(child);
});
}
这是一个接近真实代码的示例。我们使用 MathJax 创建一些 <input>
2D 向量内的 s。在我的例子中,这将与交互式图形显示集成,因此条目的值将存储在父组件的状态中,并且 Example
都可以从父级接收值并设置这些值。自 <input>
在MathJax完成排版之前,s不存在,我们必须手动管理它们。
interface Props {
setParentValue: (i: number, value: number) => void;
values: number[];
}
class Example extends React.PureComponent<Props> {
private div: HTMLDivElement;
private inputs: HTMLInputElement[];
private rg: RenderGroup;
componentDidMount() {
this.rg.ready.then(() => {
this.inputs = this.div.querySelectorAll("input");
for (let i = 0; i < this.inputs.length; ++i) {
this.inputs[i].addEventListener("change", e => this.props.setParentValue(i, e.target.value));
}
});
}
shouldComponentUpdate(nextProps) {
if (this.inputs) {
for (let i = 0; i < nextProps.values.length; ++i) {
if (this.props.values[i] !== nextProps.values[i])
this.inputs[i].value = nextProps.values[i];
}
}
return false;
}
render() {
// render only runs once, using initial values
return (
<div ref={ref => this.div = ref}>
<RenderGroup ref={ref => this.rg = ref}>
<MJX>{String.raw`
\begin{bmatrix}
\FormInput[4][matrix-entry][${this.props.values[0]}]{input1}\\
\FormInput[4][matrix-entry][${this.props.values[1]}]{input2}
\end{bmatrix}
`}</MJX>
<MJX>+</MJX>
<MJX>{String.raw`
\begin{bmatrix}
\FormInput[4][matrix-entry][${this.props.values[2]}]{input3}\\
\FormInput[4][matrix-entry][${this.props.values[3]}]{input4}
\end{bmatrix}
`}</MJX>
<MJX>=</MJX>
<MJX>{String.raw`
\begin{bmatrix}
${this.props.values[0]+this.props.values[2]}\\
${this.props.values[1]+this.props.values[3]}
\end{bmatrix}
`}</MJX>
</RenderGroup>
</div>
);
}
}
这是我的问题。
RenderGroup
很脆。例如,我不明白为什么我需要检查 if (!ref)
;但如果我省略该行,则 ref
将(由于我不明白的原因)在后续更新中变为空并导致错误。拦截ref以获取ready
Promise 似乎也很粗略。
我正在慢慢尝试将我的类组件迁移到 Hooks ;而这个isn't strictly necessary ,根据 React 团队的说法 it should be possible 。问题是函数组件没有实例,所以我不知道如何公开 .ready
父组件如 Example
。我看到有一个 useImperativeHandle
对于这种情况,这似乎取决于最终对 HTML 组件的引用。我想在 MJX
的情况下我可以引用 <span>
,但这不适用于 RenderGroup
.
强制管理输入是痛苦且容易出错的。有什么办法可以恢复 React 声明式的优点吗?
额外奖励:我还不知道如何输入 recursiveMap
适本地; TypeScript 对 fn(child)
感到愤怒线。用泛型替换 any 也很好。
最佳答案
我个人没有使用过 MathJax,但根据我的经验,处理 resolveReady
内容的“惯用 React”方式可能是通过上下文向下传递回调,让子级通知父级在加载或准备就绪时。示例(带钩子(Hook)!):
const LoadingContext = createContext(() => () => {});
const LoadingProvider = memo(LoadingContext.Provider);
function RenderGroup({ children }) {
const [areChildrenReady, setAreChildrenReady] = useState(false);
const nextChildIdRef = useRef(0);
const unfinishedChildrenRef = useRef(new Set());
const startLoading = useCallback(() => {
const childId = nextChildIdRef.current++;
unfinishedChildrenRef.current.add(childId);
setAreChildrenReady(!!unfinishedChildrenRef.current.size);
const finishLoading = () => {
unfinishedChildrenRef.current.delete(childId);
setAreChildrenReady(!!unfinishedChildrenRef.current.size);
};
return finishLoading;
}, []);
useEffect(() => {
if (areChildrenReady) {
// do whatever
}
}, [areChildrenReady]);
return (
<LoadingProvider value={startLoading}>
{children}
</LoadingProvider>
);
}
function ChildComponent() {
const startLoading = useContext(LoadingContext);
useEffect(() => {
const finishLoading = startLoading();
MathJaxReady
.then(anotherPromise)
.then(finishLoading);
}, [startLoading]);
return (
// elements
);
}
关于javascript - 惯用的 React 和大量 DOM 操作 (MathJax),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57722818/
问题是,当用户回复彼此的帖子时,我必须这样做: margin-left:40px; 对于 1 级深度 react margin-left:80px; 对于 2 层深等 但是我想让 react div
我试图弄清楚如何将 React Router 与 React VR 连接起来。 首先,我应该使用 react-router dom/native ?目前尚不清楚,因为 React VR 构建在 Rea
我是 React 或一般编码背景的新手。我不确定这些陈述之间有什么区别 import * as react from 'react' 和 import react from 'react' 提前致谢!
我正在使用最新的稳定版本的 react、react-native、react-test-renderer、react-dom。 然而,react-native 依赖于 react@16.0.0-alp
是否 react 原生 应用程序开发可以通过软件架构实现,例如 MVC、MVP、MVVM ? 谢谢你。 最佳答案 是的。 React Native 只是你提到的那些软件设计模式中的“V”。如果你考虑其
您好我正在尝试在我的导航器右按钮中绑定(bind)一个功能, 但它给出了错误。 这是我的代码: import React, { Component } from 'react'; import Ico
我使用react native创建了一个应用程序,我正在尝试生成apk。在http://facebook.github.io/react-native/docs/signed-apk-android.
1 [我尝试将分页的 z-index 更改为 0,但没有成功] 这是我的codesandbox的链接:请检查最后一个选择下拉列表,它位于分页后面。 https://codesandbox.io/s/j
我注意到 React 可以这样导入: import * as React from 'react'; ...或者像这样: import React from 'react'; 第一个导入 react
我是 react-native 的新手。我正在使用 React Native Paper 为所有屏幕提供主题。我也在使用 react 导航堆栈导航器和抽屉导航器。首先,对于导航,论文主题在导航组件中不
我有一个使用 Ignite CLI 创建的 React Native 应用程序.我正在尝试将 TabNavigator 与 React Navigation 结合使用,但我似乎无法弄清楚如何将数据从一
我正在尝试在我的 React 应用程序中进行快照测试。我已经在使用 react-testing-library 进行一般的单元测试。然而,对于快照测试,我在网上看到了不同的方法,要么使用 react-
我正在使用 react-native 构建跨平台 native 应用程序,并使用 react-navigation 在屏幕之间导航和使用 redux 管理导航状态。当我嵌套导航器时会出现问题。 例如,
由于分页和 React Native Navigation,我面临着一种复杂的问题。 单击具有类别列表的抽屉,它们都将转到屏幕 问题陈述: 当我随机点击类别时,一切正常。但是,在分页过程中遇到问题。假
这是我的抽屉导航: const DashboardStack = StackNavigator({ Dashboard: { screen: Dashboard
尝试构建 react-native android 应用程序但出现以下错误 info Running jetifier to migrate libraries to AndroidX. You ca
我目前正在一个应用程序中实现 React Router v.4,我也在其中使用 Webpack 进行捆绑。在我的 webpack 配置中,我将 React、ReactDOM 和 React-route
我正在使用 React.children 渲染一些带有 react router 的子路由(对于某个主路由下的所有子路由。 这对我来说一直很好,但是我之前正在解构传递给 children 的 Prop
当我运行 React 应用程序时,它显示 export 'React'(导入为 'React')在 'react' 中找不到。所有页面错误 see image here . 最佳答案 根据图像中的错误
当我使用这个例子在我的应用程序上实现 Image-slider 时,我遇到了这个错误。 import React,{Component} from 'react' import {View,T
我是一名优秀的程序员,十分优秀!