简体   繁体   English

React:将状态存储到模板文字

[英]React: store state to template literals

I create js code in a separate file (no matter why, I just need to understand the principle), which consists of just a literal, for example: 我在一个单独的文件中创建js代码(无论为什么,我只需要了解原理),该文件仅包含一个文字,例如:

export default `
<div>
</div>
`

and import it into the component as follows: import * as content from ./filename.js after which I can refer to him as follows, for example: document.write(content) and there are no problems with this 并将其导入到组件中,如下所示: import * as content from ./filename.js之后我可以按以下方式引用他,例如: document.write(content) ,这没有问题

But it is not at all clear to me how in such a construction it is possible to store the state. 但是我完全不清楚在这种结构中如何存储状态。

In the component where I import this code, there is a props called body 在我导入此代码的组件中,有一个称为body的道具

Is it possible to make the following construction work: ? 是否可以进行以下施工工作?

export default `
<div>
${this.props.body}
</div>
`

Sorry if I didn't write too accurately. 对不起,如果我写得不太准确。 Ready to quickly answer all questions 准备快速回答所有问题

If i see problem right, you ask not about react but ES6 template strings. 如果我发现问题正确,则您不询问反应,而是询问ES6模板字符串。 As i understand, when you write a literal string ${variable} it have context of current scope and translate to value before you export it. 据我了解,当您编写文字字符串$ {variable}时,它具有当前范围的上下文并在导出之前转换为值。 So you have only way to declare these variables inside your template file or use template engine at import side. 因此,您只有在模板文件中声明这些变量或在导入端使用模板引擎的唯一方法。

As variant, you can create proxy function 作为变体,您可以创建代理功能

//module.js
export default function(context) {
    return `test ${context.teststring} test`
}

// main.js with teststring in scope
import withContext from "./module";
document.write(withContext(this));

A template literal uses ${...} : 模板文字使用${...}

export default `
<div>
${this.props.body}
</div>
`

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

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