简体   繁体   English

像stackoverflow这样的textarea预览有

[英]textarea preview like stackoverflow have

I have a textarea , I created a preview div which only displays the text, but I want the text to have background color of grey when the sentence is between `` to display codes.我有一个textarea ,我创建了一个仅显示文本的预览 div,但是当句子介于 `` 之间时,我希望文本具有灰色背景色以显示代码。

<textarea onChange={handleChange}></textarea>

I have a div which contains pre and code block.我有一个包含precode块的 div。

<div>
 <pre>{preview}</pre>
 <code>{code}</code>
</div>

my handleChange function is:我的handleChange函数是:

const handleChange = (e) =>{
    e.preventDefault()
    setDescription(e.target.value)
    setPreview(e.target.value);

    if (e.key === '`'){
      setCode(e.target.value)
    }

}

Here, Code and preview are defined using useState在这里,代码和预览是使用useState定义的

const [preview, setPreview] = useState("");
const [code, setCode] = useState("");

Is there any way I can accomplish it?有什么办法可以实现吗?

You should probably consider using some library for this that handles all edge cases.您可能应该考虑为此使用一些库来处理所有边缘情况。

But for learning purposes you can refer to the snippet below, I've split the text by ` and wrapped all the odd index items in code .但出于学习目的,您可以参考下面的代码片段,我将文本用`拆分,并将所有奇数索引项包装在code中。

When you split the string "type `code` here" , you get this array ["type", "code", "here"] and if you observe the contents wrapped inside ` will always be at an odd index.当你拆分字符串"type `code` here"时,你会得到这个数组["type", "code", "here"]并且如果你观察到包裹在`中的内容总是在一个奇数索引处。 So, I've mapped over the array and wrapped all odd index items within code .因此,我已经映射了数组并将所有奇数索引项包装在code中。 Try spitting more such strings and you'll get more clarity on this.尝试吐出更多这样的字符串,你会更清楚这一点。

 function App() { const [content, setContent] = React.useState("Type `code` here"); return ( <div> <textarea value={content} onChange={({ target }) => setContent(target.value)} ></textarea> <p> {content .split("`") .map((c, i) => (i & 1 ? <code key={i}>{c}</code> : c))} </p> </div> ); } const root = ReactDOM.createRoot(document.getElementById("root")); root.render( <React.StrictMode> <App /> </React.StrictMode> );
 code { background: #eee; padding: 0.25rem; border-radius: 0.15rem; } textarea { width: 60ch; height: 5rem; }
 <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <div id="root"></div>

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

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