【问题标题】:content in <script> tag to ReactJS component<script> 标签中的内容到 ReactJS 组件
【发布时间】:2019-01-25 14:18:40
【问题描述】:

这是我的 HTML 代码,在此我需要取出脚本部分并将其修改为 ReactJS 并再次用作 html 中的脚本源。从那以后,我将它作为 html 本身开始,并且是 React 的新手。

<script>
  function idbOK() {
      return "indexedDB" in window;  //check whether indexeddb is supported in the browser
  }
  var db;
  var key = 100;
  $(document).ready(function() {
      if(!idbOK()) return; 
      var DBopenRequest = indexedDB.open("ora_idb3",1); 
      DBopenRequest.onupgradeneeded = function(e) {  
          var thisDB = e.target.result;
          console.log("running onupgradeneeded"); 

          if(!thisDB.objectStoreNames.contains("notes")) {  
              var notesOS = thisDB.createObjectStore("notes", {autoIncrement: true}) 
              console.log("makng a new object store notes");
              notesOS.createIndex("title","title",{unique: false});
          }
      }

      DBopenRequest.onsuccess = function(e) {  
          console.log("running onsuccess");
          db = e.target.result;
          getNote();
          $('#note').on('input propertychange change', function(){
            addNote();
         })

      }

      DBopenRequest.onerror = function(e) { 
          console.log("onerror!");
          console.dir(e);
      }

  });
</script>

我想将代码更改为 ReactJS。我是 ReactJS 的新手,发现这个复杂的移动。

【问题讨论】:

    标签: javascript jquery html reactjs indexeddb


    【解决方案1】:

    您可以通过以下方法做到这一点:

    const dbSetupScript = `function idbOK() {
      return "indexedDB" in window;  //check whether indexeddb is supported in the browser
    }
    var db;
    var key = 100;
    $(document).ready(function() {
      if(!idbOK()) return; 
      var DBopenRequest = indexedDB.open("ora_idb3",1); 
      DBopenRequest.onupgradeneeded = function(e) {  
          var thisDB = e.target.result;
          console.log("running onupgradeneeded"); 
    
          if(!thisDB.objectStoreNames.contains("notes")) {  
              var notesOS = thisDB.createObjectStore("notes", {autoIncrement: true}) 
              console.log("makng a new object store notes");
              notesOS.createIndex("title","title",{unique: false});
          }
      }
    
      DBopenRequest.onsuccess = function(e) {  
          console.log("running onsuccess");
          db = e.target.result;
          getNote();
          $('#note').on('input propertychange change', function(){
            addNote();
         })
      }
    
      DBopenRequest.onerror = function(e) { 
          console.log("onerror!");
          console.dir(e);
      }
    });`;
    

    注意:如果你想要一些变量值,可以在dbSetupScript字符串中使用${variable_name}语法。

    然后从 React 组件的 render 方法中你可以执行以下操作

    &lt;script dangerouslySetInnerHTML={{__html: dbSetupScript}} /&gt;

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-06
    • 2010-09-13
    • 2011-06-14
    • 1970-01-01
    相关资源
    最近更新 更多