简体   繁体   English

如何向React组件添加自定义脚本?

[英]How do I add a custom script to React component?

Long story short: I'm trying to add a front-end app to my portfolio site that uses React. 长话短说:我正在尝试向使用React的投资组合网站添加一个前端应用程序。 I would like to integrate the app into the component as it renders. 我想在渲染时将应用程序集成到组件中。 What I have setup right now is: 我现在设置的是:

React component: 反应组件:

class Giphy extends Component {
    constructor(props) {
        super(props);
        this.state = {src: 1}

        this.handleClick = this.handleClick.bind(this);
    }
    handleClick(event) {
        this.setState({src: event.target.value})
    }
    componentDidMount() {
        const script = document.createElement("script");

        script.type = "text/javascript";
        script.src = "/scripts/giphyLogic.js";

        document.body.appendChild(script);
    }

...and a bunch of stuff in the render() method that doesn't matter ...以及render()方法中的一堆无关紧要的东西

the script that I want to load involves a bunch of jQuery and simple JS stuff. 我要加载的脚本涉及很多jQuery和简单的JS东西。

function displayButtons() {
    $("#buttons").empty();

    for (i=0; i<buttonArray.length; i++){
        var a = $("<button type='button' class='btn btn-info'>");
        var btnID = buttonArray[i].replace(/\s+/g, "+")
        a.attr("id", btnID);
        a.text(buttonArray[i]);
        $("#buttons").append(a);
    }
}

$("#addButton").on("click", function() {
    var newButton = $(".form-control").val();
    buttonArray.push(newButton);
    displayButtons();

})

function displayGIFs() {
    $(".btn-info").on("click", function() {
        $("#resultsContainer").empty();
        var subject = $(this).attr("id");
        var giphyURL = "http://api.giphy.com/v1/gifs/search?q=" + subject + "&api_key=dc6zaTOxFJmzC";

        $.ajax({ url: giphyURL, method: "GET"}).done(function(res) {
            for (t=0; t<25; t++) {
                var rating = res.data[t].rating; 
                var image = $("<img>");

                var imgURLmoving = res.data[t].images.fixed_height.url;
                var imgURLstill = res.data[t].images.fixed_height_still.url;

                image.attr("src", imgURLstill);
                image.attr("data-still", imgURLstill);
                image.attr("data-moving", imgURLmoving);
                image.attr("data-state", "still")
                image.addClass("gif");

                $("#resultsContainer").append("<p>" + rating + "</p");
                $("#resultsContainer").append(image);
            }
        })
        $(document.body).on("click", ".gif", function() {
            var state = $(this).attr("data-state");
            if (state === "still") {
                $(this).attr("src", $(this).data("moving"));
                $(this).attr("data-state", "moving");
            } else {
                $(this).attr("src", $(this).data("still"));
                $(this).attr("data-state", "still");
            }
        })
    })
}
displayButtons();
displayGIFs();

This all works on a standalone HTML document, but I can't seem to get the script to work properly. 所有这些都可以在独立的HTML文档中使用,但是我似乎无法使脚本正常工作。 When the component loads and I inspect the page, 加载组件并检查页面时,

<script type="text/javascript" src="/scripts/giphyLogic.js"></script>

is there under the bundle.js script tag, but nothing from the script happens. 在bundle.js脚本标签下有,但是脚本没有任何反应。

I get an "Uncaught SyntaxError: Unexpected token <" error that is attributed to giphyLogic.js:1 even though in the actual .js file, that line is blank. 我收到归因于giphyLogic.js:1的“意外语法错误:意外的令牌<”错误,即使在实际的.js文件中,该行为空白。 I've looked around, and this apparently happens when a file is included that doesn't exist, but the file is definitely there. 我环顾四周,当包含的文件不存在但文件确实存在时,显然会发生这种情况。 I've double checked the path (by including an image in the same folder and loading the image successfully on the page) and it's correct. 我已经仔细检查了路径(通过将图像包含在同一文件夹中并将图像成功加载到页面上),它是正确的。

Is there a way to resolve this, or am I going to have to create methods within the React component that I'm creating? 有没有办法解决这个问题,还是我必须在正在创建的React组件中创建方法?

Do not mix jQuery and react. 不要混用jQuery并做出反应。 Learn how to use react properly by reading the well-written documentation . 阅读精心编写的文档,了解如何正确使用反应。 They can guide you through the many examples to get a simple app up and running. 他们可以指导您完成许多示例,以启动并运行一个简单的应用程序。

Once again, do NOT use jQuery and react. 再一次,不要使用jQuery并做出反应。 jQuery wants to manually manipulate the DOM, and react manages a virtual DOM. jQuery希望手动操作DOM,并做出反应来管理虚拟DOM。 The two will conflict more often than not, and you're going to have a bad time. 两者之间经常发生冲突,您将会度过一段糟糕的时光。 If you have a very deep understanding of react, there are very few scenarios in which you could maybe use some jQuery, but nearly all of the time, it is to be avoided at all costs. 如果您对反应有很深的了解,那么在极少数情况下可以使用一些jQuery,但是几乎所有时间都应不惜一切代价避免这种情况。

Obviously things like $.ajax() are fine, but for anything dealing with DOM manipulation, stay away. 显然,诸如$.ajax()类的东西很好,但是对于任何涉及DOM操作的事物,请远离。 And if you only end up using jQuery for $.ajax() calls... you should switch to a leaner library like axios or use the native fetch API. 而且,如果最终只使用jQuery来进行$.ajax()调用,则应切换到像axios这样的精简库或使用本机fetch axios API。

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

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