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

时间:2022-10-24 17:52:56

I'm trying to extend a component and override one method, but both of the below methods do not work.

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

    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";
        }
    };

Second attempt:

    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";
        }
    };

When I try to render the HelloChild, it throws the error:

当我尝试渲染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 `.

How do I extend it and only override one method?

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

1 个解决方案

#1


0  

I don't think you fail, please check the error log again, I think the problem is this.props.component.value is an object, not a string or array.

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

#1


0  

I don't think you fail, please check the error log again, I think the problem is this.props.component.value is an object, not a string or array.

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