React.Children.map recursively?

后端 未结 5 1844
青春惊慌失措
青春惊慌失措 2020-12-13 19:53

I\'m building a React Component for rendering an HTML form and I\'m finding the need to recursively iterate through all children of my parent Form component in order to add

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-13 20:29

    I've made a small library to deal with the Children structure. You can check it here:

    https://github.com/fernandopasik/react-children-utilities

    In your case you can use the method deepMap:

    import React from 'react';
    import Children from 'react-children-utilities';
    
    var newChildren = Children.deepMap(this.props.children, function(child) {
        if (is.inArray(child.type.displayName, supportedInputTypes)) {
          var extraChildProps = {
            alertColor: this.props.alertColor,
            displayErrors: this.state.displayErrors
          }
          return React.cloneElement(child, extraChildProps);
        } else {
          return child;
        }
    }.bind(this));
    

提交回复
热议问题