问题
如何确认通过 props 接收的 react 元素(例如 children
)是我的渲染方法中的给定类型?
示例:
假设我有一个 List
元素和一个 ListItem
元素。在 List
的渲染方法中,我想查找所有已传递的子项,并对属于 ListItem
的任何子项执行一些特殊操作。
我确实找到了一个可行的实现,但只是在反复试验之后。请参阅下面的代码。 ( react 15.4.2)
List.jsx
import ListItem from 'list-item';
...
React.Children.map(children, child => {
console.log(child); // function ListItem() { ... }
console.log(ListItem); // function ListItem() { ... }
if (isListItem(child)) {
return (...);
}
return child;
})
// this implementation does not work
isListItem(element) {
return (element.type === ListItem);
}
// this implementation does work, but might break if I'm using something like uglify or if I use `react-redux` and `connect()` ListItem (as that will change the display name)
isListItem(element) {
return (element.type.displayName === 'ListItem');
}
// this implementation does work
isListItem(element) {
return (element.type === (<ListItem />).type);
}
ListItem.jsx
class ListItem expends React.component {
...
}
export default ListItem;
所以,最后一个实现似乎有效,但为什么第一个实现不起作用?我在 React 文档中找不到与此相关的任何 Material ,尽管我确实找到了一些关于同一件事的堆栈溢出问题。然而,这些问题中提供的答案表明第一个实现应该有效(尽管它们适用于旧版本的 React)
相关链接
最佳答案
虽然这个问题很老,但我在使用 react-hot-loader
时遇到了这个问题花了我一段时间才找到 this GitHub issue解释为什么它会这样。
This is intended, react-hot-loader@3 patches
React.createElement(<ImportedComponent />)
is equivalent toReact.createElement(ImportedComponent)
so that it returns an element of a proxy wrapper for your components instead of the original component, this is part of allows to replace methods on the component without unmounting.
除了您发现的方法之外,RHL 现在还提供了一个 areComponentsEqual()
function with a dedicated section in their README .
import { areComponentsEqual } from 'react-hot-loader'
const element = <Component />
areComponentsEqual(element.type, Component) // true
关于javascript - 类型检查 React Children,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42769843/