2017-09-26 97 views
0

我想克隆/扩展阵营组分(不知道如果它是有状态或无状态),并通过它道具:阵营克隆组分(无状态或有状态)传递额外的道具

const Foo = (props) => { 
    return (
    <div>foo</div> 
); 
} 

class Bar extends React.Component { 
    render() { 
    return (
     <div>bar</div> 
    ) 
    } 
} 

问题是,这两个变量FooBar应当区别处理:

const FooExtended = (props, context) => { 
    return Foo(_.extend(props, additionalProps), context); 
} 

class BarExtended extends Bar { 
    constructor(props, context) { 
     super(_.extend(props, additionalProps), context); 
    } 
} 

而且没有简单的方法来知道如果一个变量Component无国籍或有状态没有做哈克toString正则表达式测试。

React.cloneElement/createElement失败,这些给我下面的错误:

React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object. You likely forgot to export your component from the file it's defined in.

那么,有没有一种简单的方法,我可以做只是cloneComponent(originalComponent, additionalProps)

+0

https://shripadk.github.io/react/docs/clone-with-props.html检查了这一点 –

+0

React.cloneElement'给我我张贴在这个问题 – Kousha

回答

1

And there is no simple way to know if a variable Component is Stateless or Statefull [...]

而且我想这就是为什么它被要求extend React.Component在某些点的原因之一,以使其更容易的区分两者。因为React本身必须能够区分它们,因为class es不能在没有new的情况下被实例化。

你可以做到以下几点:

function cloneComponent(originalComponent, additionalProps) { 
 
    if (originalComponent.prototype instanceof React.Component) { 
 
    return class extends originalComponent { 
 
     constructor(props, context) { 
 
     super(_.extend(props, additionalProps), context); 
 
     } 
 
    }; 
 
    } 
 
    return (props, context) => { 
 
    return originalComponent(_.extend(props, additionalProps), context); 
 
    }; 
 
}

因为Foo.protoype instanceof React.Componenttrue


然而,我认为这是更常见的是做这样的事情,而不是:

function addProps(Component, additionalProps) { 
    return props => <Component {...props} {...additionalProps} />; 
} 

那么就没有必要状态和无状态组件之间进行区分。 @SterlingArcher这个API已被弃用,`

+0

错误'instanceof'不起作用,这反过来使我感到困惑https://jsfiddle.net/yr32quya/。 – Kousha

+0

另外,我喜欢'addProps'但是那么上下文呢? – Kousha

+0

你正在做'Bar instanceof ...',它应该是'Bar.prototype instanceof ...'。上下文自动传递afaik。 –