2015-11-25 44 views
0

有一个主React组件和一个名为AttributeInput的子组件。 为了避免重复代码,我提取一些代码从我的主要成分,并把它放在一个方法从AttributeInput未提供反应参考子组件

我试图引用这样的代码:

{this.state.attributeInput ? <AttributeInput ref="attributeInput"/> : null} 

<div> 
    {this.refs["attributeInput"].displayInputField(
     "List Name", 
     "List Name(<15 characters - A-Z, 0-9 and _ only)", 
     this.setListName 
)} 
    {this.refs["attributeInput"].displayInputField(
     "List Description", 
     "List Description", 
     this.setListDescription 
)} 
</div> 

然而,如果this.state.attributeInput是假,AttributeInput将不会呈现。因此,当我在这里引用它,

this.refs["attributeInput"].displayInputField(
    "List Name", 
    "List Name(<15 characters - A-Z, 0-9 and _ only)", 
    this.setListName 
) 

我得到一个错误,说AttributeInput是不确定的。

如果未呈现,我可以参考AttributeInput吗? 我的方法有其他选择吗?

+1

您无法在'render'本身内部访问'refs'到其他组件。无论如何'AttributeInput'的目的是什么?你为什么要调用它的方法?你是否滥用React组件作为方法包? –

回答

0

听起来好像你正在尝试communicate between two React components,但你想共享AttributeInput组件上存在的代码和调用方法吗?

在组件之间共享代码的最简单方法是将共享代码分离到混合中。

var SharedCode = function() { 
    return { 
    displayInputField: function(name, description, other) { 
     // ... 
    } 
    }; 
}; 

然后,只需将该mixin包含在需要使用displayInputField方法的组件中即可。

var AttributeInput = React.createClass({ 
    mixins: [SharedCode] 
}); 

您已经定义并包括混合料搅拌后,您将能够在this引用新添加的属性。

return (
    <div> 
    {this.displayInputField(/* ... */)} 
    </div>  
);