react-router 4.3 js實現跳轉

蓓蕾心晴發表於2018-07-31
import React, {Component} from `react`;
import { NavLink,Link } from "react-router-dom";
import `./index.less`;
import PropTypes from `prop-types`; //這裡是重點

import logo from `../../images/hyzklogo.png`;
import logoName from `../../images/logo_name.png`;

export default class Header extends Component {
    static contextTypes = {   //這裡是重點
        router: PropTypes.object.isRequired,
    }
    constructor(props) {
        super(props);
        this.state = {
            keyword:""
        };
        this.handleToSearch=this.handleToSearch.bind(this);
        this.handleChange=this.handleChange.bind(this);
    }
    handleChange(event) {
        this.setState({keyword: event.target.value});
    }
    handleToSearch() {       this.context.router.history.push(`/news_list/search/${this.state.keyword}`)  //這裡是重點,實現跳轉
    }
    render() {
        return (
               <div className="wrapper">
                   <div className="header">
                       <div className="logo-bar">
                           <div className="container">
                               <Link to="/index"><img src={logo} alt="智庫logo" className="logo" /></Link>
                               <Link to="/index"><img src={logoName} alt="智庫" className="logo-name" /></Link>
                               <div className="search-bar">
                                   <input type="text" placeholder="搜尋感興趣的軍事資訊" value={this.state.keyword} onChange={this.handleChange}/>
                                   <div onClick={this.handleToSearch}>
                                       <i className="iconfont icon-sousuo"></i>
                                   </div>
                               </div>
                           </div>
                       </div>
                       <div className="header-bar">
                           <div className="container">
                               <ul>
                                   <li>
                                       <NavLink to="/" exact activeClassName="nav-active">首頁</NavLink>
                                   </li>
                                   <li>
                                       <NavLink to="/intro" activeClassName="nav-active">智庫概況</NavLink>
                                   </li>
                                   <li>
                                       <NavLink to="/professor_list" activeClassName="nav-active">專家團隊</NavLink>
                                   </li>
                               </ul>
                           </div>
                       </div>
                   </div>
               </div>
        );
    }
}

 

相關文章