اذهب إلى المحتوى
  • 0

إضافة jQuery إلى موقع مبني بـ React - Gatsby

Adam Ebrahim

السؤال

مرحبًا، أحاول أن أضيف بعض أكواد jquery ولكن لا أستطيع فعل ذلك في Gatsby أو بالأحرى يمكنني أن أضع الأكواد في ملف html.js ولكن يتم تنفيذ هذه الأكود قبل أن يتم عرض مكونات React (يتم عمل render لها)، قمت أيضًا بمحاولة إستخدام الخطاف componentDidMount في ملف html.js ولكن الأمر لم ينجح معي

هنا محتوى ملف html.js:

import React from "react"
import PropTypes from "prop-types"

export default class HTML extends React.Component {
  componentDidMount() {
    console.log('Hello, World!');
  }
  
  render() {
    return (
      <html {...this.props.htmlAttributes}>
        
      	<head>
          {this.props.headComponents}
        </head>
      
        <body>
          {this.props.preBodyComponents}
          <div
            key={`body`}
            id="___gatsby"
            dangerouslySetInnerHTML={{ __html: this.props.body }}
          />
          {this.props.postBodyComponents}
        </body>
      </html>
    )
  }
}

HTML.propTypes = {
  htmlAttributes: PropTypes.object,
  headComponents: PropTypes.array,
  bodyAttributes: PropTypes.object,
  preBodyComponents: PropTypes.array,
  body: PropTypes.string,
  postBodyComponents: PropTypes.array,
}

كما هو ظاهر قمت بطباعة جملة 'Hello, World!' من خلال الخطاف componentDidMount لكن لم يحدث شيء!

رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 0

يمكننا إستخدام jquery بطريقتين 

  1. الإولى من CDN وذلك كالتالي 

في ملف gatsby-ssr.js 

const React = require("react")

export const onRenderBody = ({ setHeadComponents }, pluginOptions) => {
  setHeadComponents([
    <script
      src="https://code.jquery.com/jquery-3.4.1.min.js"
      integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
      crossOrigin="anonymous">
    </script>,
  ])
}

بعد ذلك في نحتاج أن نضيف jquery إلى ويب باك وذلك في ملف gatsby-node.js كالتالي

exports.onCreateWebpackConfig = ({
  actions,
}) => {
  const { setWebpackConfig } = actions;
  setWebpackConfig({
    externals: {
      jquery: 'jQuery',
    }
  })
}

الثانيه ما إذا كان مشروعك يتضمن ملفات ال jquery يمكنك إستخدام helmet في هذه الحالة كالتالي

// layout.js
import { withPrefix } from "gatsby"
const Component = ({ children }) => (
  <>
    <Helmet>
        <script src={withPrefix('../../scripts/jquery.min.js')} type="text/javascript" />
    </Helmet>
  </>
)

 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...