javascript - 类型检查 React Children

标签 javascript html validation reactjs

问题

如何确认通过 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 to React.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.

- @nfcampos

除了您发现的方法之外,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/

相关文章:

javascript - 在 Angular.js 中实现 promise 时如何始终运行一些代码

javascript - 使用 Meteor 时如何正确地限定嵌套的#each Spacebars 迭代器?

html - 资源被解释为样式表但在控制台中以 MIME 类型文本/html 错误传输

javascript - jQuery - 隐藏前等待 2 秒

php - 从网站上抓取带有 url 的 html

java 验证包含数字的字符串并搜索以确保没有字符

javascript - 标准事件操作完成后采取行动

javascript - 删除动态附加到元素的事件监听器

ruby-on-rails - 如何在 Rails 3 中显示验证错误?

php - 如何使用PHP从WAV和FLAC文件中获取音频信息?