使用静态contextTypes进行搜索的组件

问题描述 投票:0回答:1
so far this is my search component 

import React from "react";
import PropTypes from "prop-types";

class Search extends React.Component {
  static contextTypes = {
    router: PropTypes.object.isRequired,
  };

  searchRef = React.createRef();

  handleSubmit = (e) => {
    e.preventDefault();
    const searchTerm = this.searchRef.current.value;
    // get the value of that input
    this.context.router.history.push(`/search/${searchTerm}`);
  };

  render() {
    return (
      <div className="search">
        <form onSubmit={this.handleSubmit}>
          <input
            type="text"
            ref={this.searchRef}
            placeholder="Hoppy"
            //assign that ref to a DOM node
          />
          <input type="submit" value="Search" />
        </form>
      </div>
    );
  }
}

export default Search;

我要做的是使用push方法更新浏览器的URL但是我得到的错误=警告:失败的上下文类型:上下文routerSearch中标记为必需,但其值为undefined。我已经搜索了这个错误,大多数人说这是由于特定版本的react-router所致,但是当我使用其他版本时,它没有什么区别,我该如何解决这个问题?有人可以给我举个例子吗?

javascript reactjs react-router react-component
1个回答
0
投票

为了让React Router将其API注入您的组件,您需要将<Search />组件与react-router的上下文组件一起包装-<Router />

喜欢这个:

import { BrowserRouter as Router } from "react-router-dom";


<Router>
  <Search />
</Router>

https://codesandbox.io/s/funny-mirzakhani-pi4v1?file=/src/App.js

© www.soinside.com 2019 - 2024. All rights reserved.