按键更新React组件

时间:2016-09-21 11:54:57

标签: javascript reactjs

我有一个React应用程序,它有一个打开文件的标签界面。打开文件数组如下所示:

[
  { name: 'file1', path: '/path/to/file1', fileContents: '...' },
  { name: 'file2', path: '/path/to/file2', fileContents: '...' },
  { ... }
]

将其呈现为<div>,如下所示:

render() {
  return this.state.files.map((file, i) => {
    return <div key={`tab--${file.path}`}> ... </div>;
  });
}

当我的应用程序重命名文件时,它会重新呈现整个选项卡(因为key道具由于路径更新而现在不同,因此React认为它是完全不同的组件并且处理前一个元素)。

将“file2”重命名为“file3”时,我希望我的应用将keytab--/path/to/file2更新为tab--/path/to/file3,而无需重新渲染组件 - 所以只需更新关于组件的key道具 有没有办法按key查找组件,然后更新key

1 个答案:

答案 0 :(得分:2)

不应使用密钥来访问组件。他们只是习惯于让反应跟踪该范围内的组件。我只是使用public static class WindowHelper { // https://code.google.com/p/zscreen/source/browse/trunk/ZScreenLib/Global/GraphicsCore.cs?r=1349 /// <summary> /// Get real window size, no matter whether Win XP, Win Vista, 7 or 8. /// </summary> public static Rectangle GetWindowRectangle(IntPtr handle) { if (Environment.OSVersion.Version.Major < 6) { return GetWindowRect(handle); } else { Rectangle rectangle; return DWMWA_EXTENDED_FRAME_BOUNDS(handle, out rectangle) ? rectangle : GetWindowRect(handle); } } [DllImport(@"dwmapi.dll")] private static extern int DwmGetWindowAttribute(IntPtr hwnd, int dwAttribute, out Rect pvAttribute, int cbAttribute); private enum Dwmwindowattribute { DwmwaExtendedFrameBounds = 9 } [Serializable, StructLayout(LayoutKind.Sequential)] private struct Rect { // ReSharper disable MemberCanBePrivate.Local // ReSharper disable FieldCanBeMadeReadOnly.Local public int Left; public int Top; public int Right; public int Bottom; // ReSharper restore FieldCanBeMadeReadOnly.Local // ReSharper restore MemberCanBePrivate.Local public Rectangle ToRectangle() { return Rectangle.FromLTRB(Left, Top, Right, Bottom); } } private static bool DWMWA_EXTENDED_FRAME_BOUNDS(IntPtr handle, out Rectangle rectangle) { Rect rect; var result = DwmGetWindowAttribute(handle, (int)Dwmwindowattribute.DwmwaExtendedFrameBounds, out rect, Marshal.SizeOf(typeof(Rect))); rectangle = rect.ToRectangle(); return result >= 0; } [DllImport(@"user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetWindowRect(IntPtr hWnd, out Rect lpRect); private static Rectangle GetWindowRect(IntPtr handle) { Rect rect; GetWindowRect(handle, out rect); return rect.ToRectangle(); } } 作为您的密钥(以便React不会丢失组件的跟踪)并使用ref(i)来访问组件本身(通过<div key={i} ref={(f) => this[file.name] = f} />)。

this[file.name]被更改为其他内容时,您可能需要对this[file.name]仍然指向对象进行一些清理,但我认为这会让您更接近您需要的内容。 / p>