根据官方说明:
将 React 添加到网站 https://reactjs.org/docs/add-react-to-a-website.html
我创建了 test.html
内容:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Add React in One Minute</title>
</head>
<body>
<h2>Add React in One Minute</h2>
<p>This page demonstrates using React with no build tooling.</p>
<p>React is loaded as a script tag.</p>
<!-- We will put our React component inside this div. -->
<div id="like_button_container"></div>
<!-- Load React. -->
<!-- Note: when deploying, replace "development.js" with "production.min.js". -->
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!-- Load our React component. -->
<script src="test.js"></script>
</body>
</html>
和test.js
:
'use strict';
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
componentDidMount() {
axios.get(`http://localhost:4000/api/v1/cars`)
.then(result => {
console.log(result.data[0].make);
})
}
render() {
if (this.state.liked) {
return 'You liked this.';
}
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);
}
}
const domContainer = document.querySelector('#like_button_container');
ReactDOM.render(e(LikeButton), domContainer);
上面的代码运行良好。
我可以按“赞”按钮并查看更改,还可以使用 Axios 等库。
现在我要打开http://localhost/test.html?param1=111¶m2=222并在 test.js
中获取这些 param1
和 param2
变量 - React。那可能吗?如何实现这一目标?
非常感谢
最佳答案
正如您在 ComponentDidMount
中执行 fetch
一样,您可以在同一个 lifecycle event 中检查查询参数。 。建立在 link shared by @Olian04 之上,如下所示:
componentDidMount() {
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.has("param1")) {
console.log(urlParams.get("param1"));
} else {
console.log("param1 was not found");
}
if (urlParams.has("param2")) {
console.log(urlParams.get("param2"));
} else {
console.log("param2 was not found");
}
}
关于javascript - 将 React 添加到现有页面并在 .js 中获取 URL 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57403462/