如何从自定义功能调用<Link to =''>路由转换?

时间:2019-08-16 03:37:05

标签: reactjs react-router

我在React功能组件中有一个可单击行的AntD表。我想编写一个函数,该函数将更改路由(链接到子组件),类似于单击“转到某路径”元素。我该怎么办?

<Table 
    dataSource={patientsInTable} 
    columns={columns} 
    onRow={(record, rowIndex) => { 
        return { onClick: (event) => {console.log('go'); return (<Redirect to='/dashboard' />)} }; 
    }} 
/>

2 个答案:

答案 0 :(得分:1)

在功能组件中,您可以使用重定向到另一个组件,

props.history.push('/dashboard')

但是要使用历史记录对象,我们需要使用withRouter HOC包装该组件。

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

const MyComponent = () => {
   return(
     <Table 
       dataSource={patientsInTable} 
       columns={columns} 
       onRow={(record, rowIndex) => { 
            return { onClick: (event) => {
                console.log('go'); 
                props.history.push('/dashboard');
             } 
          }; 
       }} 
     />
   )
}

export default withRouter(MyComponent)

Demo

答案 1 :(得分:0)

如果您的意思是编程,请尝试

this.props.history.push('/your-link')

编辑:已与您的代码一起更新

<Table 
    dataSource={patientsInTable} 
    columns={columns} 
    onRow={(record, rowIndex) => { 
        return { onClick: (event) => {console.log('go'); this.props.history.push('/dashboard')} }; 
    }} 
/>