首页 > 解决方案 > createClass 结果上的调用方法应该很简单

问题描述

我想在创建它之后但在渲染它之前调用一个随机组件上的方法。在渲染父级之前为父级执行子级特定计算。一个简单的静态应该可以工作。

class Container extends ReactWrapper{

    render() {
    const rClass = React.createClass(this.getCCArgs());
    var newData = rClass.expectedUtilityFunction(data); 
    // render parent with new data.
      return (<div {...this.props.data, ...newData}>
          {rClass}
      </div>);
   };
};

尝试了多种方法,总是找不到实用方法。我可以在逻辑上将事情推到最后,并添加一个方法来返回用于从输入数据创建反应实例的类,但我已经有了反应类实例。

标签: reactjs

解决方案


React.createClass弃用并从 React 16+ 中删除。所以我建议停止tring使其工作。

您的代码非常适合高阶组件

下面是示例代码(我没有测试它,所以只用作提示)

function WrappedComponent (Component, props) {
    var newData = /* Here is good place for expectedUtilityFunction code. Don't put expectedUtilityFunction function into Component, put it here, in HOC body */ 
    // render parent with new data.
    return (<div {...props.data, ...newData}>
        <Component/>
    </div>);
}

并像这样使用 HOC

class Container extends ReactWrapper{
    constructor(props) {
        supre(props);
        // Assuming that this.getCCArgs() returns component
        this.hoc = WrappedComponent (this.getCCArgs(), props);
    }

    render() {
        return this.hoc;
    }
}

推荐阅读