{...}"."/> {...}".">
search
HomeWeb Front-endFront-end Q&AHow to introduce external methods in react

How to introduce external methods in react: 1. Introduce external methods through import; 2. Introduce external methods through the life cycle in react, code such as "componentDidMount(){let scriptSrc = ['/config/jquery" .min.js', '/config/lib/codemirror.js']scriptSrc.map(res => {...}".

How to introduce external methods in react

The operating environment of this tutorial: Windows 10 system, react version 18.0.0, Dell G3 computer.

How to introduce external methods in react?

Record the introduction of external functions js in react Question

When working on a react project, sometimes you need to reference other native js modules (that is, methods)

If the js is exported through the export default of es6, then in jsx can be introduced through import;

But if the js is just a method and has not been exported through es6, etc., it must be introduced through script;

For example, I wrote a native js or in a js Using jquery to operate the node return value means that a native event is triggered when a page element is clicked. It cannot be introduced through import in jsx.

There are two ways to introduce this js

1. If you introduce

in html in your react framework 2. You can also introduce

in jsx through the life cycle of react, for example

   componentDidMount() {
        // 要引入的js文件地址
        let scriptSrc = ['/config/jquery.min.js', '/config/lib/codemirror.js']
        scriptSrc.map(res => {
            // 动态创建script标签
            var script = document.createElement('script');
            // 规则
            script.type = "text/javascript"
            // script中src只想路径
            script.src = res;
            // 追加到html的head头中
            document.head.appendChild(script);
        })
        var script = document.createElement('script')
        script.type = 'text/javascript'
        script.src = '/config/show-hint.js'
        // 追加到html中body的内
        document.body.append(script)
        var script = document.createElement('script');
        script.type = "text/javascript"
        script.src = '/config/formula.js';
        // 追加到html中body的内
        document.body.append(script);
    }

If you need to introduce several js, you need to dynamically create several script tags, otherwise the latter will overwrite the former

If you add js to the head, it is because

You must wait until all js codes are downloaded After the parsing and execution are completed, the page content begins to be displayed.

There is a pitfall when introducing

If the script introduces js in the html, its js address is

http://http://localhost:端口号/你的js名称

, that is It means that the js address that the browser is looking for is the file in the public in your project, that is, the file under the static resource, so we need to put the js into the public (under the static resource directory) and import it directly / your path.

Recommended learning: "react video tutorial"

The above is the detailed content of How to introduce external methods in react. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are the limitations of React?What are the limitations of React?May 02, 2025 am 12:26 AM

React'slimitationsinclude:1)asteeplearningcurveduetoitsvastecosystem,2)SEOchallengeswithclient-siderendering,3)potentialperformanceissuesinlargeapplications,4)complexstatemanagementasappsgrow,and5)theneedtokeepupwithitsrapidevolution.Thesefactorsshou

React's Learning Curve: Challenges for New DevelopersReact's Learning Curve: Challenges for New DevelopersMay 02, 2025 am 12:24 AM

Reactischallengingforbeginnersduetoitssteeplearningcurveandparadigmshifttocomponent-basedarchitecture.1)Startwithofficialdocumentationforasolidfoundation.2)UnderstandJSXandhowtoembedJavaScriptwithinit.3)Learntousefunctionalcomponentswithhooksforstate

Generating Stable and Unique Keys for Dynamic Lists in ReactGenerating Stable and Unique Keys for Dynamic Lists in ReactMay 02, 2025 am 12:22 AM

ThecorechallengeingeneratingstableanduniquekeysfordynamiclistsinReactisensuringconsistentidentifiersacrossre-rendersforefficientDOMupdates.1)Usenaturalkeyswhenpossible,astheyarereliableifuniqueandstable.2)Generatesynthetickeysbasedonmultipleattribute

JavaScript Fatigue: Staying Current with React and Its ToolsJavaScript Fatigue: Staying Current with React and Its ToolsMay 02, 2025 am 12:19 AM

JavaScriptfatigueinReactismanageablewithstrategieslikejust-in-timelearningandcuratedinformationsources.1)Learnwhatyouneedwhenyouneedit,focusingonprojectrelevance.2)FollowkeyblogsliketheofficialReactblogandengagewithcommunitieslikeReactifluxonDiscordt

Testing Components That Use the useState() HookTesting Components That Use the useState() HookMay 02, 2025 am 12:13 AM

TotestReactcomponentsusingtheuseStatehook,useJestandReactTestingLibrarytosimulateinteractionsandverifystatechangesintheUI.1)Renderthecomponentandcheckinitialstate.2)Simulateuserinteractionslikeclicksorformsubmissions.3)Verifytheupdatedstatereflectsin

Keys in React: A Deep Dive into Performance Optimization TechniquesKeys in React: A Deep Dive into Performance Optimization TechniquesMay 01, 2025 am 12:25 AM

KeysinReactarecrucialforoptimizingperformancebyaidinginefficientlistupdates.1)Usekeystoidentifyandtracklistelements.2)Avoidusingarrayindicesaskeystopreventperformanceissues.3)Choosestableidentifierslikeitem.idtomaintaincomponentstateandimproveperform

What are keys in React?What are keys in React?May 01, 2025 am 12:25 AM

Reactkeysareuniqueidentifiersusedwhenrenderingliststoimprovereconciliationefficiency.1)TheyhelpReacttrackchangesinlistitems,2)usingstableanduniqueidentifierslikeitemIDsisrecommended,3)avoidusingarrayindicesaskeystopreventissueswithreordering,and4)ens

The Importance of Unique Keys in React: Avoiding Common PitfallsThe Importance of Unique Keys in React: Avoiding Common PitfallsMay 01, 2025 am 12:19 AM

UniquekeysarecrucialinReactforoptimizingrenderingandmaintainingcomponentstateintegrity.1)Useanaturaluniqueidentifierfromyourdataifavailable.2)Ifnonaturalidentifierexists,generateauniquekeyusingalibrarylikeuuid.3)Avoidusingarrayindicesaskeys,especiall

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use