Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于 React.Component key属性的使用 #817

Closed
benjycui opened this issue Jan 6, 2016 · 7 comments
Closed

关于 React.Component key属性的使用 #817

benjycui opened this issue Jan 6, 2016 · 7 comments

Comments

@benjycui
Copy link
Contributor

benjycui commented Jan 6, 2016

刚才发现,在 React 中,key 应该是被视为不可读的 facebook/react#5541

然后,antd 有些组件使用了 key,如 Menu

@mark-lauq
Copy link

@benjycui 好细心

@warmhug
Copy link
Contributor

warmhug commented Jan 6, 2016

在组件运行变成实例后,key就取不到了,想取到原先设置的key,就要再设置个为类似eventKey之类的把用户设置的key拷贝存下来,组件内部都要这么做的。这么看利用key的值其实也没什么问题,因为组件不会再读取key(而会读取eventKey),当然更明确的做法是让用户直接设置eventKey即可,react-bootstrap 即是这么做。一年多前刚开始做rc组件时和 @yiminghe 讨论过这个问题了~。

@yiminghe
Copy link
Contributor

yiminghe commented Jan 6, 2016

key 在数组时是必须设置的,否则 react warning/error,所有 eventKey 没必要

@warmhug
Copy link
Contributor

warmhug commented Jan 6, 2016

key 在数组时是必须设置,是react需要的,不过我们现在是用了这个key的值,更好的做法可能是不要利用这个key,而加个类似eventKey之类。现在只用key对用户来说比较省事。

@yiminghe
Copy link
Contributor

yiminghe commented Jan 6, 2016

目标就是用户省事

@benjycui
Copy link
Contributor Author

benjycui commented Jan 7, 2016

嗯,想起了源码是用 eventKey 的。。。

key 确实会省事,但是会有个隐藏的坑。就是在用户设置 key 之后,在组件拷贝 keyeventKey 之前,key 值有可能会发生改变,如用户使用了 React.Children.toArray,see:#790 (好吧,我之前也踩了)

当然,现在改 API 也会有兼容问题,所以在不改 API 的前提下,就需要用户多加注意了,要使用 React.Children.forEach/map 去自行实现一个 toArray,如:https://github.com/react-component/util/blob/master/src/Children/mapSelf.js

如果之前已经有定论,这 issue 就先关了。

@benjycui benjycui closed this as completed Jan 7, 2016
@briefguo
Copy link

在15.6.1版本里,已经看到维护者有意去引导用户不去使用key进行逻辑处理
key={yourKey}里的yourKey,会被改写成 .$yourKey

所以我觉得Menu组件里key相关的逻辑,
不推荐使用这个key,比如selectKeys属性,
会随着react对key的改动而需要跟着强制进行修改

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants