javascript – ReactJS组件函数

前端之家收集整理的这篇文章主要介绍了javascript – ReactJS组件函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
仍然有关于ReactJS的愚蠢问题=)
有没有办法向React组件添加公共函数
我想做这样的事情:
  1. var LoginForm = React.createClass({
  2. getInitialState: function() {
  3. },render: function() {
  4. },MyFunc: function () {
  5. }
  6. })
  7. ...
  8. var login_form = LoginForm({});
  9. React.renderComponent(login_form,document.body);
  10. ...
  11. login_form.MyFunc (); <-- error

你能解释一下我做错了什么吗?

解决方法

您不应该在组件本身之外使用组件的方法(或者将其作为回调传递给子组件).您应该将这些视为私有方法.

但是,您可以使用名为statics的React功能来提供组件外部可用的功能.但是,这些应该被视为类的静态函数,因此它们无法访问组件实例的内部(例如this.props或this.state).

以下是组件的一些静态设置示例:

  1. var Component = React.createClass({
  2. statics: {
  3. // these functions are available outside the component
  4. renderToBody: function() {
  5. React.renderComponent(
  6. <Component />,document.body
  7. );
  8. }
  9. },// cannot access this function outside the component
  10. getHelloWorld: function() {
  11. return 'Hello World!';
  12. },render: function() {
  13. return (
  14. <div>{this.getHelloWorld()}</div>
  15. );
  16. }
  17. });

因此,如果我们调用React.renderComponent(Component({}),elem),那么组件将呈现为elem,但由于静态,您可以调用Component.renderToBody(),它会将组件直接呈现给< body>元件.

IE:在组件的静态对象内定义的函数可直接作为静态函数使用.但是你必须记住它们是静态的,因为它们不是实例化组件对象的一部分,它们只是你可以在类上调用函数.

反应的整个想法是组件尽可能独立.您永远不需要直接从组件外部访问组件实例函数,因为您应该做的只是更改组件的props并重新呈现它,以便在内部可以更改它.

这是一个例子:

  1. var Component = React.createClass({
  2. propTypes: {
  3. // always get in the habbit of using propTypes!
  4. message: React.PropTypes.string.isrequired,show: React.PropTypes.bool
  5. },render: function() {
  6. return (
  7. <div style={{display: this.props.show ? 'block' : 'none'}}>
  8. {this.props.message}
  9. </div>
  10. );
  11. }
  12. });

而您可能已经在组件上创建了一个方法show()(以便您可以执行component.show(true)或component.show(false)来显示/隐藏 – 而是将其作为相同结果的属性传递).

调用React.renderComponent(Component({message:’foo’,show:true}),elem)将渲染组件可见,使用show:false重新渲染将隐藏它,等等.结果相同,但带有props,这是反应方式.

猜你在找的JavaScript相关文章