您不应该在组件本身之外使用组件的方法(或将其作为回调传递给子组件)。您应该将这些视为私有方法。
但是,你可以使用的react称为一个特点statics
是提供的功能是可以从组件外。但是,这些应该被视为类的静态函数,因此它们无法访问组件实例的内部(例如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
在他们没有实例化的组件对象的一部分,它们是您可以在一流的呼叫只是功能。
React 的整个想法是组件尽可能独立。您永远不需要直接从组件外部访问组件实例函数,因为您应该做的只是更改组件的 props 并重新渲染它,以便它可以在内部进行更改。
这是一个例子:
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>
);
}
});
而您可能已经在show()
组件上创建了一个方法(以便您可以执行component.show(true)
或component.show(false)
显示/隐藏 - 您将其作为属性传递以获得相同的结果。
调用React.renderComponent(Component({message: 'foo', show: true}), elem)
将使组件可见,重新渲染show: false
将隐藏它,等等。相同的结果,但使用props,这是react方式。