Kar*_*toR 6 javascript reactjs
还有关于ReactJS的愚蠢问题=)有没有办法向React组件添加公共函数?我想做这样的事情:
var LoginForm = React.createClass({
getInitialState: function() {
},
render: function() {
},
MyFunc: function () {
}
})
...
var login_form = LoginForm({});
React.renderComponent(login_form, document.body);
...
login_form.MyFunc (); <-- error
Run Code Online (Sandbox Code Playgroud)
你能解释一下我做错了什么吗?
Mik*_*ver 13
您不应该在组件本身之外使用组件的方法(或者将其作为回调传递给子组件).您应该将这些视为私有方法.
但是,你可以使用的反应称为一个特点statics是提供的功能是可以从组件外.但是,这些应该被视为类的静态函数,因此它们无法访问组件实例的内部(例如this.propsor 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>
);
}
});
Run Code Online (Sandbox Code Playgroud)
因此,如果我们调用React.renderComponent(Component({}), elem)那么组件将呈现,elem但由于您可以调用静态Component.renderToBody(),它将直接将组件呈现给<body>元素.
IE:在组件statics对象内定义的函数可直接作为静态函数使用.然而,你必须记住,他们是static在他们没有实例化的组件对象的一部分,他们只是功能,您可以在类调用.
反应的整个想法是组件尽可能独立.您永远不需要直接从组件外部访问组件实例函数,因为您应该做的只是更改组件的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>
);
}
});
Run Code Online (Sandbox Code Playgroud)
而您可能已经在show()组件上创建了一个方法(以便您可以执行component.show(true)或component.show(false)显示/隐藏 - 而是将其作为属性传递给相同的结果.
调用React.renderComponent(Component({message: 'foo', show: true}), elem)将渲染组件可见,重新渲染show: false将隐藏它等.相同的结果,但使用道具,这是反应方式.
| 归档时间: |
|
| 查看次数: |
6155 次 |
| 最近记录: |