简体   繁体   English

通过首先存储在一个变量中,然后正确格式化,将一串代码添加到我的 html 中?

[英]Adding a string of code to my html by first storing in a variable, then formatting correctly?

I have a code stored under an exported const in a different file, however I would like to include this as an example in my html if possible...我有一个代码存储在不同文件中导出的常量下,但是如果可能的话,我想将其作为示例包含在我的 html 中...

my-consts.js我的consts.js

export const myCode = styled.div`
    margin: 100px;
    ...
`

app.js应用程序.js

import {myCode} from './my-consts';

function addCode() {
    const block = document.getElementById('block');
    block.innerHTML = myCode;
}

...

return(
    <button onClick={addCode}>Click me</button>
    <div id="block"></div>
    ...
);

This naturally doesn't work as myCode is simply a reference to some code, so I am presented with a reference code to the actual code...这自然是行不通的,因为myCode只是对某些代码的引用,所以我看到了对实际代码的引用代码......

I have also tried using <pre> around the ref to no affect.我也试过在 ref 周围使用<pre>没有影响。

My eventual goal would be like this:我的最终目标是这样的:

 <pre> export const Button = styled.button` font-size: 1.3em; background: ${props => props.primary ? "none" : "pink"}; color: ${props => props.primary ? "pink" : "white"} border: 3px solid pink; margin: 10px; cursor: pointer; ` </pre>

I will be changing the code in the display block when I click different buttons, so I do not wish to hardcode this...当我单击不同的按钮时,我将更改显示块中的代码,因此我不希望对此进行硬编码...

Expanding on the comment made by @ShubhanuSharma ( See this sandbox for a quick solution ), it turns out that it doesn't seem possible to extract code as a string from a variable;扩展@ShubhanuSharma 发表的评论(请参阅此沙箱以获取快速解决方案),结果表明似乎不可能从变量中提取代码作为字符串; ie. IE。 extracting something like const myVar = 'hello world';提取类似const myVar = 'hello world'; as a full string: "const var = 'hello world';"作为一个完整的字符串: "const var = 'hello world';" ... ...

So the next best thing is to define a const with this in, essentially copy-pasting the const into a stringified format...所以下一个最好的事情是定义一个常量,本质上是将常量复制粘贴到字符串化格式中......

export const myconsts = {
    'const1': `const myCode = styled.div\`
    margin: 100px;
    ...
    \``,
    'const2': ... 
}

and pulling them in with the function:并使用函数将它们拉入:

import {myconsts} from './file';

function addCode(code) {
    const block = document.getElementById('code-block');
    block.innerHTML = myconsts.code;
}

with the HTML:使用 HTML:

<button onClick="addCode('const1')">Click me</button>
<div id="code-block"></div>

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

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