javascript - 将 React 添加到现有页面并在 .js 中获取 URL 参数

标签 javascript html reactjs

根据官方说明:

将 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&param2=222并在 test.js 中获取这些 param1param2 变量 - 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/

相关文章:

javascript - "static"和 "non-static"在 Express 上下文中意味着什么?

javascript - 使用简写字符类的正则表达式

javascript - 将两个数组合并为一个具有相同数量对象的数组

javascript - jquery 函数不工作不会显示警报

javascript - ajax php javascript php页面打开,参数未传递

javascript - 提交 HTML 表单后从数组中提取数据(按键事件)

javascript - Reactjs-Redux : Even after user is logged in, mapStateToProps 返回用户首先被认证为false,然后为true

javascript - 使用 json html javascript 的地址簿

javascript - 如何从 discord.js 中提取消息数据?

laravel - 在 Laravel Mix 和 React 中使用 .env 常量