简体   繁体   English

在 React 中制作可选的可编辑文本字段的最佳做法是什么?

[英]What's the best practice for making an optionally editable text field in react?

So I am trying to make an interaction which is similar to the file browser in VSCode.所以我正在尝试进行类似于 VSCode 中的文件浏览器的交互。 I display a list of items, and click on an item to select it.我显示一个项目列表,然后点击一个项目到 select 它。 I want to then be able to press enter when an item is selected to make that item editable.然后我希望能够在选择一个项目时按回车键使该项目可编辑。

My first attempt was to use the contentEditable property, as it seemed the easy way to turn editing on and off on my div:我的第一次尝试是使用contentEditable属性,因为它似乎是在我的 div 上打开和关闭编辑的简单方法:

...
render(
    <div
      contentEditable={this.state.isEditable}>
      {this.state.text}
    </div>
)

But when I use this method, I get this warning:但是当我使用这种方法时,我收到了这个警告:

[Error] Warning: A component is contentEditable and contains children managed by React. [错误] 警告:一个组件是contentEditable并且包含由 React 管理的children组件。 It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated.现在您有责任保证这些节点都不会被意外修改或复制。 This is probably not intentional.这可能不是故意的。

If I understand correctly, contentEditable is breaking the convention of React, and this may cause issues if I use this method.如果我理解正确的话,contentEditable 打破了 React 的惯例,如果我使用这种方法,这可能会导致问题。

As I have read more about contentEditable in general, I have also seen that there are some issues with the HTML generated inside being inconsistent across different browsers.当我阅读更多关于contentEditable的一般内容时,我还发现内部生成的 HTML 在不同浏览器之间存在一些不一致的问题。

So my question is, what would be the standard/best practice to achieve something like this where I want to swap between a display-only element and an input element?所以我的问题是,在我想在仅显示元素和输入元素之间交换的情况下,实现类似目标的标准/最佳实践是什么? Should I use an input tag instead and disable it instead of enabling it?我应该改用输入标签并禁用它而不是启用它吗?

You can consider using input's native attributes, readonly/disabled, depends on your use-case, for example:您可以考虑使用输入的本机属性,只读/禁用,取决于您的用例,例如:

<input readOnly={!this.state.isEditable}/>

contenteditable will give you HTML, but you're not using this.state.text as HTML (just text), and as you've noted the HTML varies from browser to browser. contenteditable会给你 HTML,但你没有使用this.state.text作为 HTML(只是文本),正如你所注意到的 HTML 因浏览器而异。 I'd swap a styled input for the div :我会为div交换样式input

return this.state.isEditable
    ? <input className="styling-class" type="text" value={this.state.text} />
    : <div>{this.state.text}</div>
;

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

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