[英]textarea component with highlighted text in react js
I am looking for some good practice example to change color of text in a textarea in react js我正在寻找一些好的实践示例来更改 react js 中 textarea 中文本的颜色
i saw some example with adding div on top of textarea but how to do that in a react way我看到了一些在 textarea 顶部添加 div 的例子,但如何以一种反应方式做到这一点
To change the color of the text, we need to add html and css.要更改文本的颜色,我们需要添加 html 和 css。 We can't add that in textarea as textarea only contains text, but not html elements.
我们不能在 textarea 中添加它,因为 textarea 只包含文本,而不包含 html 元素。
So, for your usecase, what you gonna do is use a div with contenteditable instead of textarea to enter the text.因此,对于您的用例,您要做的是使用带有 contenteditable 的 div 而不是 textarea 来输入文本。 Like this
像这样
<div contentEditable></div>
Now to do in react way.现在以反应方式做。 We need to store the state which will be rendered in div.
我们需要存储将在 div 中呈现的状态。 And upon some action like selection of the text, you can insert the text wrapped around ap tag with style of text color.
并且在某些操作(例如选择文本)时,您可以插入带有文本颜色样式的 ap 标签周围的文本。
For suppose, lets assume this line, This is a sentence for demo
.对于假设,让我们假设这一行,
This is a sentence for demo
。 When user selects on sentence
, we can wrap the text with p and update the state like this - This is a <p style={{ color: 'red' }}>sentence</p> for demo
.当用户选择
sentence
,我们可以用 p 包裹文本并像这样更新状态 - This is a <p style={{ color: 'red' }}>sentence</p> for demo
。
const [state, setState] = useState('');
render (
<div contentEditable>{state}</div>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.