简体   繁体   English

有没有办法改变a的文本<h1>元素使文本不同</h1>

[英]Is there a way to change the text of a <h1> element so that the text is different

I have a program where the text will change what is displayed depending on the state, the state can be 'loading', 'updating' etc. I was wondering if there was a way to do so without needing to refresh the page.我有一个程序,其中文本将根据 state 更改显示的内容,state 可以“加载”、“更新”等。我想知道是否有办法这样做而无需刷新页面。 So if the state is loading then it will display "loading your data" and the same for other states.因此,如果 state 正在加载,那么它将显示“正在加载您的数据”,其他状态也是如此。

import "./styles.css";

const status = {
  loading: "loading your data",
  updating: "updating your data",
  updated: "your data is updated"
};

export default function App() {
  const state = "updating";

  return (
    <div className="App">
      <h1>{status.loading}</h1>
    </div>
  );
}

You will need an async function to update the current state depending on some other condition(when the data is loaded change the text to updated etc.) by using template literals between the h1 tag.您将需要异步 function 来更新当前的 state,具体取决于其他条件(加载数据时将文本更改为更新等),方法是在 h1 标记之间使用模板文字。 But looks like you are an ultimate beginner.但看起来你是一个终极初学者。 Keep up the good work.保持良好的工作。

Obviously you aren't changing the state just yet, so it will always be "updating" .显然你还没有改变 state ,所以它总是"updating" But in order to get the right message from the status dictionary based on the state, what you write is:但是为了从基于 state 的status字典中得到正确的消息,你写的是:

<h1>{status[state]}</h1>

We use bracket notation instead of dot notation to access a property when the key is a variable.当键是变量时,我们使用括号表示法而不是点表示法来访问属性。

MDN: Property accessors MDN:属性访问器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM