长话短说:我试图向使用React的投资组合网站添加一个前端应用程序。我想将应用程序集成到组件中。我有什么设置现在的问题是:如何将自定义脚本添加到React组件?
阵营组成:
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);
}
...在渲染()方法了一堆东西,这并不重要
,我希望脚本加载涉及一堆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();
这一切都适用于独立的HTML文档,但我似乎无法让脚本正常工作。当部件载荷和我检查网页,
<script type="text/javascript" src="/scripts/giphyLogic.js"></script>
是那里的bundle.js脚本标签下,但剧本没有任何反应。
即使在实际的.js文件中,该行为空,我也会得到归因于giphyLogic.js:1的“Uncaught SyntaxError:意外的令牌<”错误。我环顾四周,这显然发生在一个文件不存在的情况下,但文件肯定存在。我已经加倍检查了路径(通过在同一文件夹中包含图像并在页面上成功加载图像)并且它是正确的。
有没有办法解决这个问题,或者我将不得不在我创建的React组件中创建方法?
你为什么试图通过React动态加载脚本?没有理由这样做。 –
好吧,最简单的答案是我并不真正知道自己在做什么,并随着我的学习而去学习。真正的答案是我正在尝试在投资组合网站上做到这一点,试图通过在我的网站上托管应用程序来展示使用jQuery的能力,而不是简单地包括演示和少量图片。 –