JSX 变量更新未反映在页面上

我正在尝试将 JSX 变量添加到页面。我首先将其初始化为 null,因为它可能未被使用,但如果触发事件,我想将 JSX 添加到页面中。一旦用户完成文本输入并关闭模式窗口,处理程序就会执行。我可以成功地将他们的文本放到下面的这个处理函数中,但是由于某种原因,在模式关闭后,变量的 JSX 没有反映在当前页面上。


let other = null;


const handler = (text) => {

    other = (

        <li>

            <span className="bold">Other: </span>

            {text}}<span className="right">Price Unknown</span>

        </li>

    );

};

后来,我在我的 JSX 中简单地使用了这个变量


<div className="other">

    {other}

</div>

为什么这个更新在模态关闭后没有反映在页面上?我希望新添加的列表元素在哪里,它是空白的,好像 {other} 仍然指的是 null。这是需要重新渲染的页面的问题吗?


函数式编程
浏览 327回答 2
2回答

青春有我

您需要调用处理函数并返回要呈现的 HTML。此外,如果您尝试更新变量并渲染它,请使用setState基于类的组件或[stateName, stateUpdateMethod] = useState(null)功能组件,然后用于stateUpdateMethod触发重新渲染。import React from "react";import ReactDOM from "react-dom";const handler = (text) => <div>{text}</div>&nbsp;const App = () => handler("I am the text")const rootElement = document.getElementById("root");ReactDOM.render(&nbsp; <App />,rootElement);

哆啦的时光机

您使用变量的方式不正确。我在这里写了一个类似问题的答案。它显示了如何更新视图以及如何声明变量。请检查那里的答案,如果您仍有疑问,请告诉我。以下是那里答案的简短摘要:如果您也想更新视图(这是您的情况),您应该在设置或更改值时使用 state 和 setState 方法。例子:class MyContainer extends Component {&nbsp; &nbsp; state = { testVarible: "this is a test" };&nbsp; &nbsp; onMove = () => {&nbsp; &nbsp; &nbsp; &nbsp; console.log(this.state.testVarible);&nbsp; &nbsp; &nbsp; &nbsp; this.setState({ testVarible: "new value" });&nbsp; &nbsp; }}话虽如此,我仍然觉得你让它变得复杂。你应该做的是这个。state = { text: 'some text' };const handler = (text) => {&nbsp; this.setState({ text });};虽然 jsx 应该有这个:<div className="other">&nbsp; <li>&nbsp; &nbsp; <span className="bold">Other: </span>{this.state.text}&nbsp; &nbsp; <span className="right">Price Unknown</span>&nbsp; </li></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript