2015-09-21 39 views
3

我创建了这个小函数来查找特定type的子项。类似jQuery的方法来查找/选择React元素数组

我想能够通过jQuery,[name="example"]等属性选择孩子。有没有什么办法从jQuery中去掉字符串选择器的功能来创建一个对象映射来喂给lodash的_.find

我知道这是一个用于选择/查找/过滤数组的虚拟解决方案,但我认为它可能非常有用。我也知道,它不会找到深刻的孩子,它只会处理直接根源的孩子。

这是否存在于反应中?

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 
} 
+2

如果您使用的是现代浏览器,jQuery中的大部分选择器功能可以通过使用'document.querySelectorAll'的本地方式提供,该文件使用css选择器引擎。你也可以使用[sizzle](http://sizzlejs.com/),这是jQuery的选择器引擎的基础。 –

+1

但我想提供'this.props.children'中的HTML /元素。 – ThomasReggi

+0

@KevinB +1提到Sizzle。 ThomasReggi会检查出Sizzle,这可能是你的问题的答案。 – Wolf

回答

0

下面是我想要的仅支持元素类型的简单版本。

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

理想我能做到这一点,它会得到所有divsnameprop设置为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) 
1

有一个叫做react-query的小开源库,完全可以做到这一点。

+0

似乎反应查询被放弃,这个其他库应该做的伎俩:[茶匙](https://github.com/jquense/teaspoon) –

相关问题