内部组件无法正确呈现

时间:2017-11-24 05:29:02

标签: javascript reactjs components jsx

我已经在反应中创建了一个自定义组件。以下是该组件的代码。

import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Avatar from '../Avatar';

const propTypes = {
    classes: PropTypes.object,
    backgroundColor: PropTypes.string,
    labelText: PropTypes.string,
    onClick: PropTypes.func,
    avatarProp: PropTypes.instanceOf(Avatar)
}

export default class Chip extends React.Component {
    constructor(props){
        super(props);

        this.onClick = this.onClick.bind(this);
    }

    onClick(e) {
        if (this.props.disabled) {
          e.preventDefault();
          return;
        }

        if (this.props.onClick) {
            this.props.onClick(e);
        }
    }

    render(){

        let {
          classes,
          avatar: avatarProp,
          backgroundColor,
          labelText,
          onClick,
        } = this.props;

        let avatar = null;
        if (avatarProp && React.isValidElement(avatarProp)) {
          avatar = React.cloneElement(
            avatarProp, 
            {
                className: classNames(classes.avatar, avatarProp.props.className),
                childrenClassName: classNames(classes.avatarChildren, avatarProp.props.childrenClassName),
            });
        }

        console.log(avatarProp);

        let defaultClasses = 'chips chips-rounded';

        return (
            <div className={classNames(classes, defaultClasses)} onClick={ this.onClick }>
                {avatar}
                <span>{this.props.labelText}</span>
            </div>
        )
    }

}

Chip.propTypes = propTypes;

我已使用以下代码来使用创建的组件。

<Chip labelText="This is a sample chip" onClick={function(){console.log('This is a sample click event')}}>
    <Avatar backgroundColor="#333" size="100" />
</Chip>

但是当我检查渲染的组件时,内部组件不会被渲染。我使用控制台输出检查它返回undefined。我在这做错了什么?

1 个答案:

答案 0 :(得分:1)

“头像”会将children道具传递给Chip组件,而不会传递给avatar,因此您可以执行以下操作

render(){

    let {
      classes,
      backgroundColor,
      labelText,
      onClick,
      children
    } = this.props;

    let avatar = null;
    if (children && React.isValidElement(children)) {
      avatar = React.cloneElement(
        children, 
        {
            className: classNames(classes.avatar),
            childrenClassName: classNames(classes.avatarChildren),
        });
    }


    let defaultClasses = 'chips chips-rounded';

    return (
        <div className={classNames(classes, defaultClasses)} onClick={ this.onClick }>
            {avatar}
            <span>{this.props.labelText}</span>
        </div>
    )
}