Example #1
0
 boundMethod.bind = function(newThis, ...args) {
   // User is trying to bind() an autobound method; we effectively will
   // ignore the value of "this" that the user is trying to use, so
   // let's warn.
   if (newThis !== component && newThis !== null) {
     monitorCodeUse('react_bind_warning', { component: componentName });
     console.warn(
       'bind(): React component methods may only be bound to the ' +
       'component instance. See ' + componentName
     );
   } else if (!args.length) {
     monitorCodeUse('react_bind_warning', { component: componentName });
     console.warn(
       'bind(): You are binding a component method to the component. ' +
       'React does this for you automatically in a high-performance ' +
       'way, so you can safely remove this call. See ' + componentName
     );
     return boundMethod;
   }
   var reboundMethod = _bind.apply(boundMethod, arguments);
   reboundMethod.__reactBoundContext = component;
   reboundMethod.__reactBoundMethod = method;
   reboundMethod.__reactBoundArguments = args;
   return reboundMethod;
 };
/**
 * Assert that the props are valid
 *
 * @param {string} componentName Name of the component for error messages.
 * @param {object} propTypes Map of prop name to a ReactPropType
 * @param {object} props
 * @param {string} location e.g. "prop", "context", "child context"
 * @private
 */
function checkPropTypes(componentName, propTypes, props, location) {
  for (var propName in propTypes) {
    if (propTypes.hasOwnProperty(propName)) {
      var error;
      // Prop type validation may throw. In case they do, we don't want to
      // fail the render phase where it didn't fail before. So we log it.
      // After these have been cleaned up, we'll let them throw.
      try {
        // This is intentionally an invariant that gets caught. It's the same
        // behavior as without this statement except with a better message.
        invariant(
          typeof propTypes[propName] === 'function',
          '%s: %s type `%s` is invalid; it must be a function, usually from ' +
          'React.PropTypes.',
          componentName || 'React class',
          ReactPropTypeLocationNames[location],
          propName
        );
        error = propTypes[propName](props, propName, componentName, location);
      } catch (ex) {
        error = ex;
      }
      if (error instanceof Error && !(error.message in loggedTypeFailures)) {
        // Only monitor this failure once because there tends to be a lot of the
        // same error.
        loggedTypeFailures[error.message] = true;
        // This will soon use the warning module
        monitorCodeUse(
          'react_failed_descriptor_type_check',
          { message: error.message }
        );
      }
    }
  }
}
Example #3
0
 createClass: function(spec) {
   var Constructor = function(props) {};
   Constructor.prototype = new ReactCompositeComponentBase();
   Constructor.prototype.constructor = Constructor;
   injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor));
   mixSpecIntoComponent(Constructor, spec);
   if (Constructor.getDefaultProps) {
     Constructor.defaultProps = Constructor.getDefaultProps();
   }
   invariant(Constructor.prototype.render, 'createClass(...): Class specification must implement a `render` method.');
   if (__DEV__) {
     if (Constructor.prototype.componentShouldUpdate) {
       monitorCodeUse('react_component_should_update_warning', {component: spec.displayName});
       console.warn((spec.displayName || 'A component') + ' has a method called ' + 'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' + 'The name is phrased as a question because the function is ' + 'expected to return a value.');
     }
   }
   for (var methodName in ReactCompositeComponentInterface) {
     if (!Constructor.prototype[methodName]) {
       Constructor.prototype[methodName] = null;
     }
   }
   if (__DEV__) {
     return ReactLegacyElement.wrapFactory(ReactElementValidator.createFactory(Constructor));
   }
   return ReactLegacyElement.wrapFactory(ReactElement.createFactory(Constructor));
 },
Example #4
0
/**
 * Shared warning and monitoring code for the key warnings.
 *
 * @internal
 * @param {string} warningID The id used when logging.
 * @param {string} message The base warning that gets output.
 * @param {ReactElement} element Component that requires a key.
 * @param {*} parentType element's parent's type.
 */
function warnAndMonitorForKeyUse(warningID, message, element, parentType) {
  var ownerName = getCurrentOwnerDisplayName();
  var parentName = parentType.displayName || parentType.name;

  var useName = ownerName || parentName;
  var memoizer = ownerHasKeyUseWarning[warningID];
  if (memoizer.hasOwnProperty(useName)) {
    return;
  }
  memoizer[useName] = true;

  message += ownerName ?
    ` Check the render method of ${ownerName}.` :
    ` Check the React.render call using <${parentName}>.`;

  // Usually the current owner is the offender, but if it accepts children as a
  // property, it may be the creator of the child that's responsible for
  // assigning it a key.
  var childOwnerName = null;
  if (element &&
      element._owner &&
      element._owner !== ReactCurrentOwner.current) {
    // Name of the component that originally created this child.
    childOwnerName = getName(element._owner);

    message += ` It was passed a child from ${childOwnerName}.`;
  }

  message += ' See http://fb.me/react-warning-keys for more information.';
  monitorCodeUse(warningID, {
    component: useName,
    componentOwner: childOwnerName
  });
  console.warn(message);
}
Example #5
0
function warnForPlainFunctionType(type) {
  var isReactClass =
    type.prototype &&
    typeof type.prototype.mountComponent === 'function' &&
    typeof type.prototype.receiveComponent === 'function';
  if (isReactClass) {
    warning(
      false,
      'Did not expect to get a React class here. Use `Component` instead ' +
      'of `Component.type` or `this.constructor`.'
    );
  } else {
    if (!type._reactWarnedForThisType) {
      try {
        type._reactWarnedForThisType = true;
      } catch (x) {
        // just incase this is a frozen object or some special object
      }
      monitorCodeUse(
        'react_non_component_in_jsx',
        { version: 3, name: type.name }
      );
    }
    warning(
      false,
      'This JSX uses a plain function. Only React components are ' +
      'valid in React\'s JSX transform.'
    );
  }
}
Example #6
0
/**
 * Assert that the props are valid
 *
 * @param {string} componentName Name of the component for error messages.
 * @param {object} propTypes Map of prop name to a ReactPropType
 * @param {object} props
 * @param {string} location e.g. "prop", "context", "child context"
 * @private
 */
function checkPropTypes(componentName, propTypes, props, location) {
  for (var propName in propTypes) {
    if (propTypes.hasOwnProperty(propName)) {
      var error;
      // Prop type validation may throw. In case they do, we don't want to
      // fail the render phase where it didn't fail before. So we log it.
      // After these have been cleaned up, we'll let them throw.
      try {
        error = propTypes[propName](props, propName, componentName, location);
      } catch (ex) {
        error = ex;
      }
      if (error instanceof Error && !(error.message in loggedTypeFailures)) {
        // Only monitor this failure once because there tends to be a lot of the
        // same error.
        loggedTypeFailures[error.message] = true;
        // This will soon use the warning module
        monitorCodeUse(
          'react_failed_descriptor_type_check',
          { message: error.message }
        );
      }
    }
  }
}
Example #7
0
/**
 * Log that we're using an object map. We're considering deprecating this
 * feature and replace it with proper Map and ImmutableMap data structures.
 *
 * @internal
 */
function monitorUseOfObjectMap() {
  var currentName = getCurrentOwnerDisplayName() || '';
  if (ownerHasMonitoredObjectMap.hasOwnProperty(currentName)) {
    return;
  }
  ownerHasMonitoredObjectMap[currentName] = true;
  monitorCodeUse('react_object_map_children');
}
Example #8
0
  createClass: function(spec) {
    var Constructor = function(props, owner) {
      this.construct(props, owner);
    };
    Constructor.prototype = new ReactCompositeComponentBase();
    Constructor.prototype.constructor = Constructor;

    injectedMixins.forEach(
      mixSpecIntoComponent.bind(null, Constructor)
    );

    mixSpecIntoComponent(Constructor, spec);

    // Initialize the defaultProps property after all mixins have been merged
    if (Constructor.getDefaultProps) {
      Constructor.defaultProps = Constructor.getDefaultProps();
    }

    invariant(
      Constructor.prototype.render,
      'createClass(...): Class specification must implement a `render` method.'
    );

    if (__DEV__) {
      if (Constructor.prototype.componentShouldUpdate) {
        monitorCodeUse(
          'react_component_should_update_warning',
          { component: spec.displayName }
        );
        console.warn(
          (spec.displayName || 'A component') + ' has a method called ' +
          'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
          'The name is phrased as a question because the function is ' +
          'expected to return a value.'
         );
      }
    }

    // Reduce time spent doing lookups by setting these on the prototype.
    for (var methodName in ReactCompositeComponentInterface) {
      if (!Constructor.prototype[methodName]) {
        Constructor.prototype[methodName] = null;
      }
    }

    var descriptorFactory = ReactDescriptor.createFactory(Constructor);

    if (__DEV__) {
      return ReactDescriptorValidator.createFactory(
        descriptorFactory,
        Constructor.propTypes,
        Constructor.contextTypes
      );
    }

    return descriptorFactory;
  },
  createClass: function(spec) {
    var Constructor = function(props) {
      // This constructor is overridden by mocks. The argument is used
      // by mocks to assert on what gets mounted. This will later be used
      // by the stand-alone class implementation.
    };
    Constructor.prototype = new ReactCompositeComponentBase();
    Constructor.prototype.constructor = Constructor;

    injectedMixins.forEach(
      mixSpecIntoComponent.bind(null, Constructor)
    );

    mixSpecIntoComponent(Constructor, spec);

    // Initialize the defaultProps property after all mixins have been merged
    if (Constructor.getDefaultProps) {
      Constructor.defaultProps = Constructor.getDefaultProps();
    }

    invariant(
      Constructor.prototype.render,
      'createClass(...): Class specification must implement a `render` method.'
    );

    if (__DEV__) {
      if (Constructor.prototype.componentShouldUpdate) {
        monitorCodeUse(
          'react_component_should_update_warning',
          { component: spec.displayName }
        );
        console.warn(
          (spec.displayName || 'A component') + ' has a method called ' +
          'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
          'The name is phrased as a question because the function is ' +
          'expected to return a value.'
         );
      }
    }

    // Reduce time spent doing lookups by setting these on the prototype.
    for (var methodName in ReactCompositeComponentInterface) {
      if (!Constructor.prototype[methodName]) {
        Constructor.prototype[methodName] = null;
      }
    }

    if (__DEV__) {
      return ReactLegacyDescriptor.wrapFactory(
        ReactDescriptorValidator.createFactory(Constructor)
      );
    }
    return ReactLegacyDescriptor.wrapFactory(
      ReactDescriptor.createFactory(Constructor)
    );
  },
Example #10
0
  withContext: function(newContext, scopedCallback) {
    monitorCodeUse('react_with_context', {newContext: newContext});

    var result;
    var previousContext = ReactContext.current;
    ReactContext.current = assign({}, previousContext, newContext);
    try {
      result = scopedCallback();
    } finally {
      ReactContext.current = previousContext;
    }
    return result;
  }
/**
 * Given a `prevElement` and `nextElement`, determines if the existing
 * instance should be updated as opposed to being destroyed or replaced by a new
 * instance. Both arguments are elements. This ensures that this logic can
 * operate on stateless trees without any backing instance.
 *
 * @param {?object} prevElement
 * @param {?object} nextElement
 * @return {boolean} True if the existing instance should be updated.
 * @protected
 */
function shouldUpdateReactComponent(prevElement, nextElement) {
  if (prevElement != null && nextElement != null) {
    var prevType = typeof prevElement;
    var nextType = typeof nextElement;
    if (prevType === 'string' || prevType === 'number') {
      return (nextType === 'string' || nextType === 'number');
    } else {
      if (nextType === 'object' &&
          prevElement.type === nextElement.type &&
          prevElement.key === nextElement.key) {
        var ownersMatch = prevElement._owner === nextElement._owner;
        var prevName = null;
        var nextName = null;
        var nextDisplayName = null;
        if (__DEV__) {
          if (!ownersMatch) {
            if (prevElement._owner != null &&
                prevElement._owner.getPublicInstance() != null &&
                prevElement._owner.getPublicInstance().constructor != null) {
              prevName =
                prevElement._owner.getPublicInstance().constructor.displayName;
            }
            if (nextElement._owner != null &&
                nextElement._owner.getPublicInstance() != null &&
                nextElement._owner.getPublicInstance().constructor != null) {
              nextName =
                nextElement._owner.getPublicInstance().constructor.displayName;
            }
            if (nextElement.type != null &&
                nextElement.type.displayName != null) {
              nextDisplayName = nextElement.type.displayName;
            }
            monitorCodeUse(
              'react_should_update_owner_is_useful',
              {
                key: prevElement.key,
                prevOwner: prevName,
                nextOwner: nextName,
                nextDisplayName: nextDisplayName
              }
            );
          }
        }
        return ownersMatch;
      }
    }
  }
  return false;
}
Example #12
0
  createClass: function(spec) {
    var Constructor = function(props, owner) {
      this.construct(props, owner);
    };
    Constructor.prototype = new ReactCompositeComponentBase();
    Constructor.prototype.constructor = Constructor;

    var ConvenienceConstructor = ReactDescriptor.createFactory(Constructor);

    // TODO: Move statics off of the convenience constructor. That way the
    // factory can be created independently from the main class.

    injectedMixins.forEach(
      mixSpecIntoComponent.bind(null, ConvenienceConstructor)
    );

    mixSpecIntoComponent(ConvenienceConstructor, spec);

    invariant(
      Constructor.prototype.render,
      'createClass(...): Class specification must implement a `render` method.'
    );

    if (__DEV__) {
      if (Constructor.prototype.componentShouldUpdate) {
        monitorCodeUse(
          'react_component_should_update_warning',
          { component: spec.displayName }
        );
        console.warn(
          (spec.displayName || 'A component') + ' has a method called ' +
          'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
          'The name is phrased as a question because the function is ' +
          'expected to return a value.'
         );
      }
    }

    // Reduce time spent doing lookups by setting these on the prototype.
    for (var methodName in ReactCompositeComponentInterface) {
      if (!Constructor.prototype[methodName]) {
        Constructor.prototype[methodName] = null;
      }
    }

    return ConvenienceConstructor;
  },
Example #13
0
  _warnIfContextsDiffer: function(ownerBasedContext, parentBasedContext) {
   invariant(ownerBasedContext !== undefined, "Owner based context is required parameter");
   invariant(parentBasedContext !== undefined, "Parent based ontext is required parameter");
   var ownerKeys = Object.keys(ownerBasedContext).sort();
   var parentKeys = Object.keys(parentBasedContext).sort();
   if (ownerKeys.length != parentKeys.length || ownerKeys.toString() != parentKeys.toString()) {
     var message = ("owner based context (keys: " +
       Object.keys(ownerBasedContext) + ") does not equal parent based" +
       " context (keys: "+Object.keys(parentBasedContext)+")" +
       " while mounting " +
       (this._instance.constructor.displayName || 'ReactCompositeComponent'));
     console.warn(message);
     monitorCodeUse('contexts_differ', {
       ownerBasedKeys: Object.keys(ownerBasedContext),
       parentBasedKeys: Object.keys(parentBasedContext),
       mounting: (this._instance.constructor.displayName || 'ReactCompositeComponent')
     });
   }
 },
Example #14
0
function warnForLegacyFactoryCall() {
  if (!ReactLegacyDescriptorFactory._isLegacyCallWarningEnabled) {
    return;
  }
  var owner = ReactCurrentOwner.current;
  var name = owner && owner.constructor ? owner.constructor.displayName : '';
  if (!name) {
    name = 'Something';
  }
  if (legacyFactoryLogs.hasOwnProperty(name)) {
    return;
  }
  legacyFactoryLogs[name] = true;
  warning(
    false,
    name + ' is calling a React component directly. ' +
    'Use a factory or JSX instead. See: http://fb.me/react-legacyfactory'
  );
  monitorCodeUse('react_legacy_factory_call', { version: 3, name: name });
}
Example #15
0
function putListener(id, registrationName, listener, transaction) {
  if (__DEV__) {
    // IE8 has no API for event capturing and the `onScroll` event doesn't
    // bubble.
    if (registrationName === 'onScroll' &&
        !isEventSupported('scroll', true)) {
      monitorCodeUse('react_no_scroll_event');
      console.warn('This browser doesn\'t support the `onScroll` event');
    }
  }
  var container = ReactMount.findReactContainerForID(id);
  if (container) {
    var doc = container.nodeType === ELEMENT_NODE_TYPE ?
      container.ownerDocument :
      container;
    listenTo(registrationName, doc);
  }
  transaction.getPutListenerQueue().enqueuePutListener(
    id,
    registrationName,
    listener
  );
}
Example #16
0
  var warnIfUnmounted = function(instance, key) {
    if (instance.__hasBeenMounted) {
      return;
    }
    var name = instance.constructor.displayName || 'Unknown';
    var owner = ReactCurrentOwner.current;
    var ownerName = (owner && owner.constructor.displayName) || 'Unknown';
    var warningKey = key + '|' + name + '|' + ownerName;
    if (hasWarnedOnComponentType.hasOwnProperty(warningKey)) {
      // We have already warned for this combination. Skip it this time.
      return;
    }
    hasWarnedOnComponentType[warningKey] = true;

    var context = owner ? ' in ' + ownerName + '.' : ' at the top level.';
    var staticMethodExample = '<' + name + ' />.type.' + key + '(...)';

    monitorCodeUse('react_descriptor_property_access', { component: name });
    console.warn(
      'Invalid access to component property "' + key + '" on ' + name +
      context + ' See http://fb.me/react-warning-descriptors .' +
      ' Use a static method instead: ' + staticMethodExample
    );
  };
Example #17
0
  createClass: function(spec) {
    var Constructor = function(props, context) {
      // This constructor is overridden by mocks. The argument is used
      // by mocks to assert on what gets mounted.

      // Wire up auto-binding
      if (this.__reactAutoBindMap) {
        bindAutoBindMethods(this);
      }

      this.props = props;
      this.context = context;
      this.state = null;

      // ReactClasses doesn't have constructors. Instead, they use the
      // getInitialState and componentWillMount methods for initialization.

      var initialState = this.getInitialState ? this.getInitialState() : null;
      if (__DEV__) {
        // We allow auto-mocks to proceed as if they're returning null.
        if (typeof initialState === 'undefined' &&
            this.getInitialState._isMockFunction) {
          // This is probably bad practice. Consider warning here and
          // deprecating this convenience.
          initialState = null;
        }
      }
      invariant(
        typeof initialState === 'object' && !Array.isArray(initialState),
        '%s.getInitialState(): must return an object or null',
        Constructor.displayName || 'ReactCompositeComponent'
      );

      this.state = initialState;
    };
    Constructor.prototype = new ReactClassComponent();
    Constructor.prototype.constructor = Constructor;

    injectedMixins.forEach(
      mixSpecIntoComponent.bind(null, Constructor)
    );

    mixSpecIntoComponent(Constructor, spec);

    // Initialize the defaultProps property after all mixins have been merged
    if (Constructor.getDefaultProps) {
      Constructor.defaultProps = Constructor.getDefaultProps();
    }

    if (__DEV__) {
      // This is a tag to indicate that the use of these method names is ok,
      // since it's used with createClass. If it's not, then it's likely a
      // mistake so we'll warn you to use the static property, property
      // initializer or constructor respectively.
      if (Constructor.getDefaultProps) {
        Constructor.getDefaultProps.isReactClassApproved = {};
      }
      if (Constructor.prototype.getInitialState) {
        Constructor.prototype.getInitialState.isReactClassApproved = {};
      }
    }

    invariant(
      Constructor.prototype.render,
      'createClass(...): Class specification must implement a `render` method.'
    );

    if (__DEV__) {
      if (Constructor.prototype.componentShouldUpdate) {
        monitorCodeUse(
          'react_component_should_update_warning',
          { component: spec.displayName }
        );
        console.warn(
          (spec.displayName || 'A component') + ' has a method called ' +
          'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
          'The name is phrased as a question because the function is ' +
          'expected to return a value.'
        );
      }
    }

    // Reduce time spent doing lookups by setting these on the prototype.
    for (var methodName in ReactClassInterface) {
      if (!Constructor.prototype[methodName]) {
        Constructor.prototype[methodName] = null;
      }
    }

    // Legacy hook
    Constructor.type = Constructor;
    if (__DEV__) {
      try {
        Object.defineProperty(Constructor, 'type', typeDeprecationDescriptor);
      } catch (x) {
        // IE will fail on defineProperty (es5-shim/sham too)
      }
    }

    return Constructor;
  },
Example #18
0
function assertValidProps(e){e&&(invariant(null==e.children||null==e.dangerouslySetInnerHTML,"Can only set one of `children` or `props.dangerouslySetInnerHTML`."),__DEV__&&e.contentEditable&&null!=e.children&&console.warn("A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional."),invariant(null==e.style||"object"==typeof e.style,"The `style` prop expects a mapping from style properties to values, not a string."))}function putListener(e,t,n,r){__DEV__&&("onScroll"!==t||isEventSupported("scroll",!0)||(monitorCodeUse("react_no_scroll_event"),console.warn("This browser doesn't support the `onScroll` event")));var o=ReactMount.findReactContainerForID(e);if(o){var i=o.nodeType===ELEMENT_NODE_TYPE?o.ownerDocument:o;listenTo(t,i)}r.getPutListenerQueue().enqueuePutListener(e,t,n)}function validateDangerousTag(e){hasOwnProperty.call(validatedTagCache,e)||(invariant(VALID_TAG_REGEX.test(e),"Invalid tag: %s",e),validatedTagCache[e]=!0)}function ReactDOMComponent(e){validateDangerousTag(e),this._tag=e,this.tagName=e.toUpperCase()}var CSSPropertyOperations=require("CSSPropertyOperations"),DOMProperty=require("DOMProperty"),DOMPropertyOperations=require("DOMPropertyOperations"),ReactBrowserComponentMixin=require("ReactBrowserComponentMixin"),ReactComponent=require("ReactComponent"),ReactBrowserEventEmitter=require("ReactBrowserEventEmitter"),ReactMount=require("ReactMount"),ReactMultiChild=require("ReactMultiChild"),ReactPerf=require("ReactPerf"),assign=require("Object.assign"),escapeTextForBrowser=require("escapeTextForBrowser"),invariant=require("invariant"),isEventSupported=require("isEventSupported"),keyOf=require("keyOf"),monitorCodeUse=require("monitorCodeUse"),deleteListener=ReactBrowserEventEmitter.deleteListener,listenTo=ReactBrowserEventEmitter.listenTo,registrationNameModules=ReactBrowserEventEmitter.registrationNameModules,CONTENT_TYPES={string:!0,number:!0},STYLE=keyOf({style:null}),ELEMENT_NODE_TYPE=1,omittedCloseTags={area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0},VALID_TAG_REGEX=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,validatedTagCache={},hasOwnProperty={}.hasOwnProperty;ReactDOMComponent.displayName="ReactDOMComponent",ReactDOMComponent.Mixin={mountComponent:ReactPerf.measure("ReactDOMComponent","mountComponent",function(e,t,n){ReactComponent.Mixin.mountComponent.call(this,e,t,n),assertValidProps(this.props);var r=omittedCloseTags[this._tag]?"":"</"+this._tag+">";return this._createOpenTagMarkupAndPutListeners(t)+this._createContentMarkup(t)+r}),_createOpenTagMarkupAndPutListeners:function(e){var t=this.props,n="<"+this._tag;for(var r in t)if(t.hasOwnProperty(r)){var o=t[r];if(null!=o)if(registrationNameModules.hasOwnProperty(r))putListener(this._rootNodeID,r,o,e);else{r===STYLE&&(o&&(o=t.style=assign({},t.style)),o=CSSPropertyOperations.createMarkupForStyles(o));var i=DOMPropertyOperations.createMarkupForProperty(r,o);i&&(n+=" "+i)}}if(e.renderToStaticMarkup)return n+">";var a=DOMPropertyOperations.createMarkupForID(this._rootNodeID);return n+" "+a+">"},_createContentMarkup:function(e){var t=this.props.dangerouslySetInnerHTML;if(null!=t){if(null!=t.__html)return t.__html}else{var n=CONTENT_TYPES[typeof this.props.children]?this.props.children:null,r=null!=n?null:this.props.children;if(null!=n)return escapeTextForBrowser(n);if(null!=r){var o=this.mountChildren(r,e);return o.join("")}}return""},receiveComponent:function(e,t){(e!==this._currentElement||null==e._owner)&&ReactComponent.Mixin.receiveComponent.call(this,e,t)},updateComponent:ReactPerf.measure("ReactDOMComponent","updateComponent",function(e,t){assertValidProps(this._currentElement.props),ReactComponent.Mixin.updateComponent.call(this,e,t),this._updateDOMProperties(t.props,e),this._updateDOMChildren(t.props,e)}),_updateDOMProperties:function(e,t){var n,r,o,i=this.props;for(n in e)if(!i.hasOwnProperty(n)&&e.hasOwnProperty(n))if(n===STYLE){var a=e[n];for(r in a)a.hasOwnProperty(r)&&(o=o||{},o[r]="")}else registrationNameModules.hasOwnProperty(n)?deleteListener(this._rootNodeID,n):(DOMProperty.isStandardName[n]||DOMProperty.isCustomAttribute(n))&&ReactComponent.BackendIDOperations.deletePropertyByID(this._rootNodeID,n);for(n in i){var s=i[n],l=e[n];if(i.hasOwnProperty(n)&&s!==l)if(n===STYLE)if(s&&(s=i.style=assign({},s)),l){for(r in l)!l.hasOwnProperty(r)||s&&s.hasOwnProperty(r)||(o=o||{},o[r]="");for(r in s)s.hasOwnProperty(r)&&l[r]!==s[r]&&(o=o||{},o[r]=s[r])}else o=s;else registrationNameModules.hasOwnProperty(n)?putListener(this._rootNodeID,n,s,t):(DOMProperty.isStandardName[n]||DOMProperty.isCustomAttribute(n))&&ReactComponent.BackendIDOperations.updatePropertyByID(this._rootNodeID,n,s)}o&&ReactComponent.BackendIDOperations.updateStylesByID(this._rootNodeID,o)},_updateDOMChildren:function(e,t){var n=this.props,r=CONTENT_TYPES[typeof e.children]?e.children:null,o=CONTENT_TYPES[typeof n.children]?n.children:null,i=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,a=n.dangerouslySetInnerHTML&&n.dangerouslySetInnerHTML.__html,s=null!=r?null:e.children,l=null!=o?null:n.children,p=null!=r||null!=i,u=null!=o||null!=a;null!=s&&null==l?this.updateChildren(null,t):p&&!u&&this.updateTextContent(""),null!=o?r!==o&&this.updateTextContent(""+o):null!=a?i!==a&&ReactComponent.BackendIDOperations.updateInnerHTMLByID(this._rootNodeID,a):null!=l&&this.updateChildren(l,t)},unmountComponent:function(){this.unmountChildren(),ReactBrowserEventEmitter.deleteAllListeners(this._rootNodeID),ReactComponent.Mixin.unmountComponent.call(this)}},assign(ReactDOMComponent.prototype,ReactComponent.Mixin,ReactDOMComponent.Mixin,ReactMultiChild.Mixin,ReactBrowserComponentMixin),module.exports=ReactDOMComponent;
Example #19
0
  createClass: function(spec) {
    var Constructor = function() {};
    Constructor.prototype = new ReactCompositeComponentBase();
    Constructor.prototype.constructor = Constructor;

    var ConvenienceConstructor = function(props, children) {
      var instance = new Constructor();
      instance.construct.apply(instance, arguments);
      return instance;
    };
    ConvenienceConstructor.componentConstructor = Constructor;
    Constructor.ConvenienceConstructor = ConvenienceConstructor;
    ConvenienceConstructor.originalSpec = spec;

    injectedMixins.forEach(
      mixSpecIntoComponent.bind(null, ConvenienceConstructor)
    );

    mixSpecIntoComponent(ConvenienceConstructor, spec);

    invariant(
      Constructor.prototype.render,
      'createClass(...): Class specification must implement a `render` method.'
    );

    if (__DEV__) {
      if (Constructor.prototype.componentShouldUpdate) {
        monitorCodeUse(
          'react_component_should_update_warning',
          { component: spec.displayName }
        );
        console.warn(
          (spec.displayName || 'A component') + ' has a method called ' +
          'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
          'The name is phrased as a question because the function is ' +
          'expected to return a value.'
         );
      }
    }

    // Expose the convience constructor on the prototype so that it can be
    // easily accessed on descriptors. E.g. <Foo />.type === Foo.type and for
    // static methods like <Foo />.type.staticMethod();
    // This should not be named constructor since this may not be the function
    // that created the descriptor, and it may not even be a constructor.
    ConvenienceConstructor.type = Constructor;
    Constructor.prototype.type = Constructor;

    // Reduce time spent doing lookups by setting these on the prototype.
    for (var methodName in ReactCompositeComponentInterface) {
      if (!Constructor.prototype[methodName]) {
        Constructor.prototype[methodName] = null;
      }
    }

    if (__DEV__) {
      Constructor.prototype = createMountWarningMembrane(Constructor.prototype);
    }

    return ConvenienceConstructor;
  },