您不應該在組件本身之外使用組件的方法(或通過將其作爲回調傳遞給子組件)。您應該將這些視爲私人方法。
但是,您可以使用名爲statics
的React功能來提供爲可從組件外部獲得的功能。但是,這些應該像一個類的靜態函數一樣對待,因此他們無法訪問組件實例的內部(例如this.props
或this.state
)。
下面是一些靜態設置的組件的例子:
var Component = React.createClass({
statics: {
// these functions are available outside the component
renderToBody: function() {
React.renderComponent(
<Component />,
document.body
);
}
},
// cannot access this function outside the component
getHelloWorld: function() {
return 'Hello World!';
},
render: function() {
return (
<div>{this.getHelloWorld()}</div>
);
}
});
所以,如果我們稱之爲React.renderComponent(Component({}), elem)
然後組件將渲染elem
但由於靜態的,你可以叫Component.renderToBody()
,它會直接呈現組件到<body>
元素。
IE:組件的statics
對象中定義的函數可直接作爲靜態函數使用。但是你必須記住它們是static
,它們是而不是實例化組件對象的一部分,它們只是你可以在類中調用的函數。
與反應的整個想法是組件儘可能獨立。您不應該直接從組件外部訪問組件實例函數,而應該改變組件的道具並重新渲染它,以便在內部更改。
這裏有一個例子:儘管您可能已經創建的組件上的一個方法show()
代替
var Component = React.createClass({
propTypes: {
// always get in the habbit of using propTypes!
message: React.PropTypes.string.isRequired,
show: React.PropTypes.bool
},
render: function() {
return (
<div style={{display: this.props.show ? 'block' : 'none'}}>
{this.props.message}
</div>
);
}
});
(這樣你就可以做component.show(true)
或component.show(false)
顯示/隱藏 - 你,而不是把它作爲一個屬性對於同樣的結果。
調用React.renderComponent(Component({message: 'foo', show: true}), elem)
將呈現組件可見,重新渲染與show: false
將其隱藏,等結果相同,但與道具,這是反應的方式。
非常感謝Mike,你幫了我很多!我能問最後一個問題嗎?據我瞭解,我可以將許多組件安裝到一個節點上?所以我可以叮them他們?例如,如果我裝備了3個可靠的配件,然後想隱藏第二個配件。 – KaronatoR 2014-10-05 15:52:19
您只能在給定的html元素上安裝一個組件。但是,處理多個組件的最佳方法之一是安裝一個父組件,然後將其他所有需要的東西放在該父組件的子組件中。但是,您可以迭代和裝載同一組件的多個實例。在反應中,這很簡單,就像迭代和推入組件到一個數組,然後在一個組件的'render'函數內渲染數組,例如'