【问题标题】:How do I add links to these buttons in React.js如何在 React.js 中添加指向这些按钮的链接
【发布时间】:2019-08-20 17:27:38
【问题描述】:

我想使用反应路由器链接到其他组件。我想将链接添加到按钮。

正如您在下面的代码中看到的那样,我想转到另一个组件而不是 google.com 链接,假设我有一个 ./starter 组件

【问题讨论】:

  • 不确定我是否理解,但将您的按钮包含在 LINK 中会有所帮助吗?
  • 只导入这个可以使用上面的代码吗?导入 { Route, Link, BrowserRouter as Router } from 'react-router-dom'

标签: javascript reactjs react-router


【解决方案1】:

您必须从 react-router-dom 导入链接,而不是使用 window.location.href 我们使用 <Link to='/path'>

import React, { Component } from 'react';
import { Link } from "react-router-dom";
import SECOND from './data/second';

class Seconds extends Component{
    render(){
        const{title, image, link}=this.props.second;
        return(
            <div style={{display: 'inline-block', width: 300, margin: 10}}>
            *//this is where i want to add the router links to other component, how do I do it??    
<Link to={link}><button><img src={image} alt='profile' style={{width: 90, height: 70, borderRadius: 5}}/><aside>{title}</aside>
                </button></Link>
            </div>
        )
    }
}

现在您可以将 app.js 包装在 Router 中,并使用 Route 标签处理路径以加载组件。

 import React, {Component} from 'react';
 import First from './First';
 import './App.css';
 import Second from './Second';
 import { BrowserRouter as Router, Route } from "react-router-dom";
 import MyComponent from '/path';

    class App extends Component{
       render(){      
          return(
             <Router>
              <hr/>
               <First/>
              <hr/>
              <Second/>
              <Route path='/yourpath' component={MyComponent} />
             </Router>
          )
      }
    }
    export default App;

希望对你有帮助!!! :)

【讨论】:

  • 我还应该更改 SECONDS.js 文件中的链接吗?我上面的第二个文件
  • 我按照你说的做了,还有 SECONDS.js 文件的链接,但是当我点击链接时,我没有被重定向,地址栏中的 url 变为“localhost:3000/components/course
  • @helloTerminal 你能分享你在codepen或jsbin中的代码吗?
  • 是的,它现在可以工作了,至少现在可以打开了。但我想去另一个页面,比如隐藏 文件。它是一个餐厅菜单应用程序,所以当我点击开胃菜时,它会显示开胃菜的菜肴。
  • 我做到了。顺便说一句,你能告诉我如何在新页面中打开它吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-08
  • 1970-01-01
  • 1970-01-01
  • 2016-08-23
  • 2011-08-15
  • 1970-01-01
相关资源
最近更新 更多