显示变量名称的模板文字 - React.js

template literals to display the variable name - React.js

在下面的代码中,我需要根据要传递的道具在 <h1> 中显示文本。 如果 props == "a" 文本应来自 text_a,如果 props == "b" 文本来自 text_b

const Header = (props) => {

const text_a = "Lorem ipsum dolor";
const text_b = "Lorem"

return (
<h1>{here should be a text from const}</h1>
);
}

我知道我可以使用三元运算符,但我想知道在这种情况下是否可以使用模板文字:

<h1>{`text_${props}`}</h1>

但在这种情况下,它按字面意思显示 "text_a" 或 "text_b" 但不是分配给变量的内容。

感谢您的帮助。

如果我理解这个问题,您想根据传递给道具的值进行渲染,例如:

const TEXT = {
  text_a: "Lorem ipsum dolor",
  text_b: "Lorem",
};

const Header = (props) => {
  return <h1>{TEXT[props.text] || "Default Text"}</h1>;
};

// "Lorem ipsum dolor"
<Header text="text_a" />;