React.Children.map recursively?

后端 未结 5 1834
青春惊慌失措
青春惊慌失措 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:21

    This thread actually misses the right answer:

    const mapRecursive = (children, callback) => (
      React.Children.map(
        children,
        child => (
          child.props.children
            ? [callback(child), mapRecursive(child.props.children, callback)]
            : callback(child)
        ),
      )
    );
    
    0 讨论(0)
  • 2020-12-13 20:21

    Short answer to this is that its not currently possible as of React 0.14. As FakeRainBrigand mentioned, its more than likely a code smell anyway, so it should prompt a reevaluation of your implementation.

    0 讨论(0)
  • 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));
    
    0 讨论(0)
  • 2020-12-13 20:32

    While not baked into React, this is certainly possible:

    import React from "react";
    
    function recursiveMap(children, fn) {
      return React.Children.map(children, child => {
        if (!React.isValidElement(child)) {
          return child;
        }
    
        if (child.props.children) {
          child = React.cloneElement(child, {
            children: recursiveMap(child.props.children, fn)
          });
        }
    
        return fn(child);
      });
    }
    
    0 讨论(0)
  • 2020-12-13 20:43

    If you're looking to push props into a set of children under your component "automatically", you can also use context. This allows you to "give" properties, functions, etc. to child components by providing them from the parent with childContextTypes and getChildContext(), and having the child "request" them with contextTypes.

    0 讨论(0)
提交回复
热议问题