如何创建我可以扩展的反应基础组件?

时间:2016-08-04 01:43:26

标签: javascript reactjs react-jsx

我正在尝试扩展组件并覆盖一个方法,但以下两种方法都不起作用。

    var Hello = React.createClass( {
        getName: function() { throw "This method not implemented" },
        render: function() {
            return <this.props.component.slug className='text'>
                {this.props.component.value}{this.getName()}
            </this.props.component.slug>;
        }
    });

    class HelloChild extends Hello {
        constructor(props) {
          super(props);
        }

        getName()
        {
          return "Child";
        }
    };

第二次尝试:

    class Hello extends React.Component {
        getName() { throw "This method not implemented" }
        render() {
            return <this.props.component.slug className='text'>
                {this.props.component.value}{this.getName()}
            </this.props.component.slug>;
        }
    };

    class HelloChild extends Hello {
        constructor(props) {
          super(props);
        }

        getName()
        {
          return "Child";
        }
    };

当我尝试渲染HelloChild时,它会抛出错误:

Uncaught Invariant Violation: Objects are not valid as a React child
(found: object with keys {}). If you meant to render a collection of 
children, use an array instead or wrap the object using 
createFragment(object) from the React add-ons. Check the render method
of `bound `.

如何扩展它并仅覆盖一种方法?

1 个答案:

答案 0 :(得分:0)

我不认为你失败了,请再次检查错误日志,我认为问题是this.props.component.value是一个对象,而不是字符串或数组。