jQuery-Like 查找方式/Select React 元素数组

jQuery-Like Way to Find / Select Array of React Elements

我创建了这个小函数来查找特定 type 的 children。

我希望能够通过 属性 select children,例如 jQuery、[name="example"]。有什么方法可以从 jQuery 中剥离字符串 select 或功能来创建一个 object 映射来提供给 lodash 的 _.find?

我意识到这是 select 搜索/查找/过滤数组的虚假解决方案,但我认为它非常有用。我也知道它不会找到 deep children,它只会处理直接根 children.

这是否已经存在于 React 中?

function containsElement (element, children) {
  var result = []
  element = _.flatten([element])
  if (React.isValidElement(children) && !_.isArray(children)) {
    var contains = _.contains(element, children.type)
    if (contains) return children
    return false
  } else if (!React.isValidElement(children) && !_.isArray(children)) {
    return false
  }
  children.forEach(function (child) {
    var isElm = React.isValidElement(child)
    var contains = _.contains(element, child.type)
    if (isElm && contains) {
      result.push(child)
    }
  })
  if (!result.length) return false
  return result
}

这是我想要的只支持元素类型的简单版本。

selectElements('div, span', this.props.children)

理想情况下,我可以做到这一点,它会得到所有 divsname prop 设置为 hello

selectElements('div[name="hello"]', this.props.children)

这是完整的示例,(jsbin)

var selectElements = function (selectorString, reactElements) {
  var selectors = selectorString.split(',')
  selectors = _.map(selectors, function (item) {
    return item.replace(/^\s+|\s$/, '')
  })
  return _.filter(reactElements, function (reactElement) {
    return _.contains(selectors, reactElement.type)
  })
}

var OnlyElements = React.createClass({
  displayName: 'OnlyElements',
  getInitialState: function () {
    return {
      children: this.props.children
    }
  },
  componentWillMount: function () {
    this.setState({
      children: selectElements(this.props.allow, this.props.children)
    })
  },
  render: function () {
    return (
      <div>
        {this.state.children}
      </div>
    )
  }
})

var Test = React.createClass({
  displayName: 'Test',
  render: function () {
    return (
      <OnlyElements allow='div'>
        <span>Alpha</span>
        <div>Beta</div>
        <span>Gamma</span>
      </OnlyElements>
    )
  }
})

React.render(<Test/>, document.body)

有一个名为 react-query 的小型开源库可以做到这一点。

编辑:react-query 存储库已被所有者存档。它现在是只读的。