关于 ReactJS 仍然有愚蠢的问题 =) 有什么办法可以给 React 组件添加公共(public)函数吗? 我正在尝试做这样的事情:
var LoginForm = React.createClass({
getInitialState: function() {
},
render: function() {
},
MyFunc: function () {
}
})
...
var login_form = LoginForm({});
React.renderComponent(login_form, document.body);
...
login_form.MyFunc (); <-- error
你能解释一下我做错了什么吗?
最佳答案
您不应该在组件本身之外使用组件的方法(或将其作为回调传递给子组件)。您应该将这些视为私有(private)方法。
但是,您可以使用 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
将隐藏它,等等。相同的结果,但有 Prop ,这是 react 方式。
关于javascript - ReactJS 组件函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26201801/