所以我试着用Reaction、MathJax和MathJs为一个学校项目展示一些数学知识, 代码如下:

const InputForm = () => {

    let latex;
    let node;
    let inicial;
//    MathJax.typesetClear();

    let parenthesis = 'keep'
    let implicit = 'hide'
    
    //'sqrt(75 / 3) + det([[-1, 2], [3, 1]]) - sin(pi / 4)^2'
    
    const [inputExpressionText, setInputExpressionText, ] = useState(initial);
    
    function initial(){
      node = math.parse('sqrt(75 / 3) + det([[-1, 2], [3, 1]]) - sin(pi / 4)^2')
      latex = node ? node.toTex({parenthesis: parenthesis, implicit: implicit}) : ''
      console.log('Node en estado inicial:', node)
      console.log('LaTeX en estado inicial:', latex)
      
      return 'sqrt(75 / 3) + det([[-1, 2], [3, 1]]) - sin(pi / 4)^2';
    }

    useEffect(() => {
      //OnInput();
    },[inputExpressionText,])

    
  
  
  

    

const OnInput = function () {
  
  console.log(inputExpressionText);
  inicial = document.getElementById("input")
  node = null;

  try {
    console.log("antes de node initial", inicial.value);
    console.log("antes de node", node);
    node = math.parse(inicial.value)
    console.log("después de node", node);
    
  }
  catch (err) {
    console.log("No entro a node = math",   )
    console.log(err.toString())
  }

  try {
    // export the expression to LaTeX
    latex = node ? node.toTex({parenthesis: parenthesis, implicit: implicit}) : ''
    console.log('LaTeX expression dentro de funcion:', latex)

    // display and re-render the expression
    
  }
  catch (err) {
  }
  console.log("lates en fuera del try-catch",latex)
}
  console.log("lates xfinal",latex)
  console.log("inputExpressionText ", inputExpressionText)
    return (
        <table className=' table  justify-content-between  '>
          <tbody>
              <tr>
                  <th>Expression</th>
                  <td><input type="text"  onInput={(e) =>{
                          setInputExpressionText(e.target.value);
                          OnInput()
                        }} id="input" value={inputExpressionText}/></td>
              </tr>
              <tr>
                  <th>Pretty print</th>
                  <td><PrettyInput latex={latex}/></td>
              </tr>
              <tr>
                  <th>Result</th>
                  <td><Result input={node} /></td>
              </tr>
          </tbody>
        </table>
    )
}

export default InputForm

问题出在这一部分

try {
    // export the expression to LaTeX
    latex = node ? node.toTex({parenthesis: parenthesis, implicit: implicit}) : ''
    console.log('LaTeX expression inside function:', latex)

    // display and re-render the expression
    
  }
  catch (err) {
  }
  console.log("lates en fuera del try-catch",latex)
}
  console.log("lates xfinal",latex)

当LaTeX Variale获得函数内部的Tex时, console.log('LaTeX expression inside function:', latex)进行确认,Console显示相应的Tex值.

但是在OnInput函数之外再次调用时,它显示了未定义的代码中断.

我曾try 在here中使用建议的示例MathJs,将其改编为Reaction组件.

该方法只有在使用VITE时添加LIVE时才有效,但如果重新加载则停止工作,因为它显示未加载DOM.

我真的被困住了

推荐答案

解释

这是因为常量只在try块中具有上下文.如果您希望在块之外可以访问它,则需要在块之前声明它并相应地设置它.

有两种主要的方法可以做到这一点,要么使用State,要么使用let.

Here's an example with useState:

//make sure to import {useState} from 'react' to use this
//declaring the variable outside of the block will allow it to be used anywhere
[latex, setLatex] = useState('')

try {
    // export the expression to LaTeX
    setLatex(node ? node.toTex({parenthesis: parenthesis, implicit: implicit}) : '')
    console.log('LaTeX expression inside function:', latex)

    // display and re-render the expression
    
  }
  catch (err) {
  }
  console.log("lates en fuera del try-catch",latex)
}
  console.log("lates xfinal",latex)

Here is an example with let(this will not persist like state though,将在每次重新渲染时转储)

let latex = ''

try {
    // export the expression to LaTeX
    latex = node ? node.toTex({parenthesis: parenthesis, implicit: implicit}) : ''
    console.log('LaTeX expression inside function:', latex)

    // display and re-render the expression
    
  }
  catch (err) {
  }
  console.log("lates en fuera del try-catch",latex)
}
  console.log("lates xfinal",latex)

更新(第三个选项)##

您也可以使用函数来执行此操作,例如:

const Latex = () => {
 try {
    // export the expression to LaTeX
    return node ? node.toTex({parenthesis: parenthesis, implicit: implicit}) : ''
    console.log('LaTeX expression inside function:', latex)

    // display and re-render the expression
    
  }
  catch (err) {
     return 'Error'
  }
}

然后,您可以这样使用它:

const ExmapleComponent = () => {
  //can put latex function here or in a helper file 
  const latex = Latex()

  return <div> jsx here </div>
}

Note to author: Welcome to stackoverflow!
:-) happy coding and hope this helps!

Javascript相关问答推荐

使用useup时,React-Redux无法找到Redux上下文值

过滤对象数组并动态将属性放入新数组

为什么当我解析一个promise时,输出处于挂起状态?

如何从隐藏/显示中删除其中一个点击?

如何在 cypress 中使用静态嵌套循环

如何通过使用vanilla JS限制字体大小增加或减少两次来改变字体大小

Javascript json定制

如何控制Reaction路由加载器中的错误状态?

环境值在.js文件/Next.js中不起作用

将异步回调转换为异步生成器模式

使用Document.Evaluate() Select 一个包含撇号的HTML元素

如何使用<;Link>;执行与JS Reaction中的";window.Location=/GameOverDied;";类似的操作?

如何在Java脚本中对数据进行签名,并在PHP中验证签名?

在JavaScript中将Base64转换为JSON

如何在Highlihte.js代码区旁边添加行号?

我如何才能获得价值观察家&对象&S的价值?

不允许在对象文本中注释掉的属性

:host::ng-Deep不将样式应用于material 复选框

观察子组件中的@Output事件emits 器?

如何在不获取其子元素的文本内容的情况下获取元素的文本内容?