英文:
Make react render the closing tag for inputs?
问题
我有一个特殊的要求。我的网站是用React构建的,我希望人们能够复制公共网站的HTML到他们自己的React组件中。
我遇到的唯一问题是,当由React渲染时,输入框没有闭合标签。
这两种都是有效的HTML
<input id="input-1" value="foo">
<input id="input-2" value="foo" />
然而,只有第二种在直接粘贴到React组件中时起作用。有办法强制React在我的网站上为输入框呈现闭合标签吗?
英文:
I have an unusual requirement. My site is build with React and I want people to be able to copy the public website's HTML into their own React components.
The only issue that I'm having is inputs do not have a closing tag when rendered by React.
Both of these are valid HTML
<input id="input-1" value="foo">
<input id="input-2" value="foo" />
However only the 2nd one will work if pasted directly into a React component. Is there a way to force React to render the closing tag for inputs on my site?
答案1
得分: 1
考虑通过类似 html-tidy 的工具处理复制的 HTML 源代码字符串。如果想在浏览器中进行格式化,请考虑使用 prettier。查看下面的示例。祝好运!
<!-- 开始代码片段: js 隐藏: false 控制台: true babel: false -->
<!-- 语言: lang-js -->
const output = prettier.format("<input type='text' name='username'>", {
parser: "html",
plugins: prettierPlugins,
});
// 发送到服务器或更新剪贴板。
console.log(output)
<!-- 语言: lang-html -->
<script src="https://unpkg.com/prettier@2.8.7/standalone.js"></script>
<script src="https://unpkg.com/prettier@2.8.7/parser-html.js"></script>
<!-- 结束代码片段 -->
英文:
Consider running the copied html source string through a tool like html tidy. If you'd like to do the formatting in the browser, consider prettier. See example below. Good Luck!
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const output = prettier.format("<input type='text' name='username'>", {
parser: "html",
plugins: prettierPlugins,
});
// Send to server or update your clipboard.
console.log(output)
<!-- language: lang-html -->
<script src="https://unpkg.com/prettier@2.8.7/standalone.js"></script>
<script src="https://unpkg.com/prettier@2.8.7/parser-html.js"></script>
<!-- end snippet -->
答案2
得分: 0
要正确理解这一点,用户可以将HTML贴到您的应用中,它需要渲染为JSX?您面临的问题是用户可以添加非自闭合的HTML输入标签,但在渲染JSX时会有问题(因为它们需要是自闭合的)?
您可以进行检查,看看输入的标签是否是输入,并且如果它不是自闭合的,然后自行关闭它。这看起来可能是这样的(假设您将字段存储在某个变量中):
if(var.substring(1,6) == "input" && var[var.length-2]!="/"){
var= var.slice(0, var.length-1)+"/"+var[var.length-1]
}
英文:
To understand this correctly, users can post the HTML into your app, and it needs to be rendered as JSX? And the issue you're facing is that users can add non self-closing HTML input tags, but that'll be an issue when rendering JSX (as they need to be self closing)?
You could perform a check to see if the tag being entered is an input, and if it isn't self-closing, and then close it yourself. That would look something like this (assuming you have the field in some var):
if(var.substring(1,6) == "input" && var[var.length-2]!="/"){
var= var.slice(0, var.length-1)+"/"+var[var.length-1]
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论