I have a little app that takes user input, and I want to show them a little preview as they type (exactly as Stackoverflow does it).
I try something like this:
ReactDOM.render(
<div>{user_input}</div>,
document.getElementById('preview')
);
It works great until I try to add a new line, react it ignores and just renders a white space. But if I do it on vanilla javascript:
var content = document.createElement('div');
content.innerText = user_input;
document.getElementById('preview').appendChild(content);
Doing it like this does the trick and every line break gets automatically turned into a <br>
tag.
Is there a way to set innerText on react or should I just go with the vanilla solution?
Is there a setback in using innerText?
I have a little app that takes user input, and I want to show them a little preview as they type (exactly as Stackoverflow does it).
I try something like this:
ReactDOM.render(
<div>{user_input}</div>,
document.getElementById('preview')
);
It works great until I try to add a new line, react it ignores and just renders a white space. But if I do it on vanilla javascript:
var content = document.createElement('div');
content.innerText = user_input;
document.getElementById('preview').appendChild(content);
Doing it like this does the trick and every line break gets automatically turned into a <br>
tag.
Is there a way to set innerText on react or should I just go with the vanilla solution?
Is there a setback in using innerText?
Share Improve this question asked Mar 17, 2017 at 0:27 Marco A. MartinezMarco A. Martinez 511 gold badge2 silver badges7 bronze badges 1-
It sounds like all of your code isn't "inside" react ponents. In general, you should probably only have one
ReactDOM.render()
Here's a link to React's forms page facebook.github.io/react/docs/forms.html as well as a codepen example of showing a preview of a controlled ponent's value codepen.io/anon/pen/MpOvVw – James Ganong Commented Mar 17, 2017 at 1:00
3 Answers
Reset to default 2using this is more suitable for keeping the indentation and line breaks:
white-space: pre-wrap;
it not only keeps the line-break, but also maintains the spaces
so if you text has
<span id="preview-message" style={{ whiteSpace: 'pre-wrap' }}>
... white space maintains between dots ...
</span>
or
<span id="preview-message" style={{ whiteSpace: 'pre-wrap' }}>
hello everyone...
spaces here will be maintain too
new line here will maintain too
</span>
The code below may be what you need.
var user_inputs = ['line1', 'line2'];
var inputs = user_inputs.map(function(user_input, idx){
return <div key={idx}>{user_input}</div>
});
ReactDOM.render(
<div className="root">{inputs}</div>,
document.getElementById('preview')
);
For the block in which the text is located, set the css rule:
white-space: pre-line;
in your case:
ReactDOM.render(
<div style={{white-space: pre-line}}>{user_input}</div>,
document.getElementById('preview')
);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744170995a4561532.html
评论列表(0条)