React 绑定到 reactDOM 之外的 HTML 元素

React bind to HTML element outside of reactDOM

我有一个非常复杂的 MathJax 渲染方程,其中包含交互式元素。这是在反应组件内呈现的,但是,MathJax 与反应完全不兼容。

所以我现在拥有一个 React 应用程序,它呈现带有交互元素(按钮、输入)的 MathJax 元素。

尽管这是一个很大的禁忌,但最安全的方法是什么:

  1. 更新输入字段值
  2. 将 onClick 动作绑定到按钮

它们是否成为组件状态的一部分?

我应该在更新状态的 React 组件中使用标准 js(document.querySelectorAll 和 addEventListener)还是有更好的方法来实现这个?

感谢您的帮助,输入!

请记住,除了重写 mathJax,我的手在这件事上束手无策。

Should I use standard js (document.querySelectorAll and addEventListener) inside the react component that update the state or is there a better way to achieve this?

是的,但至少对容器使用 refs 而不是 document.querySelectorAll,然后在该容器内工作(通过 Element#querySelectorAll 等):

When to Use Refs

There are a few good use cases for refs:

  • Managing focus, text selection, or media playback.
  • Triggering imperative animations.
  • Integrating with third-party DOM libraries.

(我强调第三点)

该页面的简单示例,稍作调整:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.mathJaxRef = React.createRef(); // ***
  }
  componentDidMount() {
    // Use `this.mathJaxRef.current`, which will be the `div` below, to do what
    // you need to, including hooking up event handlers if you cannot do so in the
    // usual React way
  }
  render() {
    return <div ref={this.mathJaxRef}>(MathJax stuff here)</div>;
  }
}