【问题标题】:Redirect to another component by clicking a button which is a part of existing component通过单击作为现有组件一部分的按钮重定向到另一个组件
【发布时间】:2019-10-01 08:44:42
【问题描述】:

我是新来的反应。我试图通过单击一个按钮来重定向到一个组件,该按钮是现有渲染组件的一部分。 现在我希望当我单击按钮时,应该呈现新组件并且应该隐藏现有组件(按钮也是)。

render(){
    return(

            <div className='container'>
            <table className='table table-striped'>
                <thead>
                    <tr>
                        <th>User_Id</th>
                        <th>User_Name</th>
                        <th>Email</th>
                    </tr>
                </thead>
                <tbody>
                    {this.state.arr.map((card)=>{
                        return(
                            <tr>
                                <td>{card.user_id}</td>
                                <td>{card.user_name}</td>
                                <td>{card.email}</td>
                                <td>
                                    <button className="btn btn-outline-primary ml-2 my-2 my-sm-0">Edit</button>
   //click here(the Edit button) to Redirect to another component
                                </td>
                                <td><button className="btn btn-outline-primary ml-2 my-2 my-sm-0">Delete</button></td>
                            </tr>       
                    ) })}
                </tbody>
             </table>
        </div>
    )

}

而要渲染的组件是-

export default class Edit extends Component{
    render(){
      return(
        <div>
          <h1>Edit User.</h1>
        </div>
       )
    }
 }

【问题讨论】:

  • 请用路由react-router-dom显示你的App.js

标签: javascript reactjs react-router jsx


【解决方案1】:
import { Route } from 'react-router-dom'

const Button = () => (
  <Route render={({ history}) => (
    <button
      type='button'
      onClick={() => { history.push('/new-location') }}
    >
      Click Me!
    </button>
  )} />
)

【讨论】:

  • 指导我应该把这段代码放在哪里。还有什么需要
【解决方案2】:

react-router-dom 有一个 Link 组件,它自己处理这个问题。您所要做的就是在 to 属性下提供它应该重定向到的 URL。只需将 button 元素替换为 Link 组件即可:

import { Link } from 'react-router-dom';

<Link to="/url-to-edit" className="btn btn-outline-primary ml-2 my-2 my-sm-0">Edit</Link>

More about the Link component.

【讨论】:

  • @MrigankShekharShringi 您的应用程序中有某种Router 组件吗?您介意使用该代码更新您的原始帖子吗?
猜你喜欢
  • 1970-01-01
  • 2020-05-17
  • 2019-12-18
  • 1970-01-01
  • 2018-01-08
  • 2019-08-17
  • 2020-07-18
  • 2023-01-21
  • 2021-01-24
相关资源
最近更新 更多