简体   繁体   English

Meteor:使用反应类中的方法

[英]Meteor: Using methods from react classes

In meteor, how do I use a method inside a react class? 在meteor中,如何在react类中使用方法?

I want to trigger a method inside a react class with a keypress, but cant seem to access it with class.method() 我想用一个按键在一个反应​​类中触发一个方法,但似乎无法用class.method()访问它

In toolbar.js: 在toolbar.js中:

import React, { Component } from 'react';

class Toolbar extends Component {
  addSection(){
    alert("add section");
  };
  render(){
    return (
      <div className="toolbar">
        <button onClick={this.addSection.bind(this)}>add section</button>
      </div>
    );
  }
}

export default Toolbar;

In main.js: 在main.js中:

import React from 'react';
import ReactDOM from 'react-dom';
import Toolbar from './components/toolbar';

const App = () => {
  return (
    <div>
        <Toolbar />
    </div>
  );
};

Meteor.startup(() => {
  ReactDOM.render(<App />, document.querySelector('.container'));
  $(document).on('keyup', function(e) {
    if (e.ctrlKey && e.keyCode == 49) { // ctrl+1
      Toolbar.addSection(); //errormsg: toolbar.addsection is not a function
    }
  });
});

Any help is greatly appreciated. 任何帮助是极大的赞赏。 Thank you 谢谢

First , This is React - If you ever find yourself using jQuery, you're probably doing it wrong. 首先 ,这是React - 如果您发现自己使用jQuery,那么您可能做错了。

Second , (and this might just be my opinion) but you should always keep things that are related to a component contained within the component. 第二 ,(这可能只是我的意见),但你应该始终保持所涉及包含在组件中的一个组件的东西。 It's cleaner and you don't have to go all around your application just to figure out where that keypress is happening. 它更清洁,你不必全面了解你的应用程序只是为了弄清楚按键发生的位置。 It should be as close to the code using it or displaying it as possible. 它应该尽可能接近使用它的代码或尽可能地显示它。

Third , You need to be aware when your component has mounted, and when that component is not on the screen. 第三 ,您需要知道何时安装了组件,以及何时该组件不在屏幕上。 Maybe your ctrl+1 doesn't become relevant until later on after somebody has "logged in" or something. 也许你的ctrl + 1直到后来有人“登录”之后才会变得相关。 So your eventListener should mount and dismount with the component using it. 因此,您的eventListener应该使用它来安装和卸载组件。

class Application extends React.Component {
  constructor(props) {
    super(props)

    this.addSection     = this.addSection.bind(this)     // This is not "needed" - but I'm doing it anyways because I can.
    this.keydownHandler = this.keydownHandler.bind(this) // See comment from @dfsq
  }

  componentDidMount() {
    document.addEventListener('keydown', this.keydownHandler)
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.keydownHandler)
  }

  addSection() {
    alert("add section")
  }

  keydownHandler(event) {
    if(event.keyCode===49 && event.ctrlKey)
      this.addSection()
  }

  render() {
    return (
      <div>
        <p>Press Ctrl+1</p>
      </div>
    )
  }
}

Here is a working CodePen. 这是一个有效的CodePen。


To use your code as an example: 以您的代码为例:

in toolbar.js : toolbar.js

import React, { Component } from 'react';

class Toolbar extends Component {
  constructor(props) {
    super(props)

    this.addSection     = this.addSection.bind(this)     // This is not "needed" - but I'm doing it anyways because I can.  I think from now on I'm going to bind all of my functions like this.  Any comment on this would be interesting.
    this.keydownHandler = this.keydownHandler.bind(this) // See comment from @dfsq
  }

  componentDidMount() {
    document.addEventListener('keydown', this.keydownHandler)
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.keydownHandler)
  }

  addSection() {
    alert("add section")
  }

  keydownHandler(event) {
    if(event.keyCode===49 && event.ctrlKey)
      this.addSection()
  }

  render(){
    return (
      <div className="toolbar">
        <button onClick={this.addSection.bind(this)}>add section</button>
      </div>
    )
  }
}

export default Toolbar;
  1. add ReactJS Lifecycle Functions 添加ReactJS Lifecycle Functions
  2. add constructor to fix the React, removeEventListener and bind(this) gotcha ... here is some more reading on this 添加constructor来修复React, removeEventListener and bind(this) gotcha ...这里有更多的阅读

in main.js : main.js

import React from 'react'
import ReactDOM from 'react-dom'
import Toolbar from './components/toolbar'

const App = () => {
  return (
    <div>
        <Toolbar />
    </div>
  )
}

Meteor.startup(() => {
  ReactDOM.render(<App />, document.querySelector('.container'))
})

I feel it important to stress a key concept in this answer. 我觉得在这个答案中强调一个关键概念很重要。 As a rule of thumb in React, if you're using jQuery, you're probably doing it wrong. 作为React的经验法则,如果你使用jQuery,你可能做错了。 React is designed very well and usually, there are very good design decisions that went into why React works the way that it does. React的设计非常好,通常,有很好的设计决策可以解释为什么React会以它的方式工作。 So, if you need to use jQuery for a little bit, while you're still learning React, that's okay (I did it too for a few days shhh... don't tell anyone ). 所以,如果你需要稍微使用jQuery,当你还在学习React时, 那没关系 (我也做了几天嘘......不要告诉任何人 )。 But, I think that in the long run, you will find that after a while you really have no need for jQuery when you're using React properly. 但是,我认为从长远来看,你会发现,当你正确使用React时,你真的不需要jQuery。

Another thing. 另一件事。 StackOverflow is great, but sometimes other venues are more appropriate for certain types of questions and advice. StackOverflow很棒,但有时其他场地更适合某些类型的问题和建议。 Two communities that have really helped me are the Meteor Forums and this React Chatroom . 真正帮助过我的两个社区是流星论坛React Chatroom Both communities are Extremely friendly. 两个社区都非常友好。 If you ever go to the Reactiflux help channel, say hi to Acemarke for me (he basically lives there) - at first, I seriously thought he was some kind of AI that Facebook designed to answer questions about React (I'm not joking, I actually thought for a while until his notable friendly humor kicked in). 如果你去Reactiflux帮助频道,请向我说Acemarke(他基本上住在那里) - 起初,我认真地认为他是某种人工智能,Facebook设计来回答有关React的问题(我不是在开玩笑,我实际上想了一会儿,直到他引人注目的友好幽默踢出来)。

Also, as a style note (and this is completely opinion) - stop using semicolons. 另外,作为样式注释(这完全是意见) - 停止使用分号。 It's okay now . 现在没关系 You actually have to make less decisions if you just stop using them. 如果你停止使用它们,你实际上必须做出更少的决定。 Try it for a week and you'll see the light. 尝试一个星期,你会看到光。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM