簡體   English   中英

從HTML文件使用React調用.js文件中的Javascript函數

[英]Call Javascript function in .js file with React from HTML file

我還沒有找到這個特定的問題,所以這里是:

說我有一個HTML文件。 在這個HTML文件中,我在body-element中有一些React類和函數。 一種功能是呈現表單。 例如:

renderForm: function() {
      return (
      <div className="form_div">
        Movie search: <input type="text" className="query"></input>
        <button onClick={this.search} className="submit">Search</button>
      </div>
    );
  },

現在。 我也有一個.js文件。 在此文件中,我具有完成的功能“搜索”,用於處理用戶輸入並將其傳遞到數據庫/ API /要搜索的內容。 這是一個相當大的功能。

我可以在HTML文件中使用React代碼調用此.js文件中的Search函數嗎?

目標是使用React處理渲染,使用JS處理功能。

這可能嗎(我不是問這是否是好習慣)?

當然可以。 分離功能是非常普遍和好的做法。 只要確保將js文件包含在html文件中即可。

是的,只需確保將該函數附加到您的React組件(以便您可以通過this來訪問它)或直接使用該函數( search而不是this.search )(如果要使其保持全局(或可能是從模塊導入))。 。

我會說將其用作外部函數更容易:

renderForm: function() {
  return (
    <div className="form_div">
      Movie search: <input type="text" className="query"></input>
      <button onClick={search} className="submit">Search</button>
    </div>          /* ^------ search comes from a script that's loaded before this code so we can just call it */
  );
}

如果search的邏輯更籠統或與您要創建的組件不相關,則這將是一種更好的方法,因為它可以為您提供較松散的耦合


如果搜索取決於特定組件(需要this綁定),則需要將其附加到您的React組件。 實際語法取決於您使用的是ES6類還是React.createClass

一種使用類的方法是圍繞全局搜索創建一個包裝方法,該方法將使用適當的上下文進行調用:

class MyComponent extends React.Component {
  constructor() {
    // ...
  }

  search(...args) {
    search.apply(this, ...args); // <--- Call the global search but bind `this` to the React component instance.
  }

  // now you can use this.search in renderForm
  renderForm() { ... }
}

您還可以將search直接附加到組件的原型 ,而不使用包裝函數:

class MyComponent extends React.Component {
  // ...

  // you can use this.search in renderForm because it will be found on the prototype
  renderForm() { ... }
}

MyComponent.prototype.search = search; // <-- attach global search to the prototype of your component

就使用React.createClass ,您只需將對全局search的引用附加到傳入的對象即可。任何在對象上被稱為方法的函數都會自動this對象設置為該對象:

var MyComponent = React.createClass({

  search: search, // <-- attach global search to your component,

  // now you can use this.search in renderForm because it is a method of your component
  renderForm() { ... }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM