将道具传递给包装在 withRouter() 函数中的反应组件

Passing props to a react component wrapped in withRouter() function

我正在使用 React-Router v4 在我的 React 应用程序中导航。以下是包装在 withRouter() 函数中的组件,使其能够在单击时更改路由:

const LogoName = withRouter(({history, props}) => (
  <h1
    {...props}
    onClick={() => {history.push('/')}}>
    BandMate
  </h1>
));

如您所见,我将 props 传递给组件,我需要它来更改组件的 class。这里的问题是 props<LogoName> 组件中的 undefined。当我单击另一个组件时,我需要能够更改此组件的 class,如下所示:

<LogoName className={this.state.searchOpen ? "hidden" : ""} />
<div id="search-container">
  <SearchIcon
    onClick={this.handleClick}
    className={this.state.searchOpen ? "active" : ""} />
  <SearchBar className={this.state.searchOpen ? "active" : ""}/>
</div>

以下是我处理点击的方式。基本上只是设置状态。

constructor(){
  super();
  this.state = {
    searchOpen: false
  }
}

handleClick = () => {
  this.setState( {searchOpen: !this.state.searchOpen} );
}

有没有办法让我将 props 传递给包装在 withRouter() 函数中的组件,或者有没有类似的方法来创建一个能够使用 React 导航的组件-路由器并仍然收到道具?

提前致谢。

你很接近,只需在你的函数签名中传播道具:

const LogoName = withRouter(({ history, ...props }) => (
  <h1
    {...props}
    onClick={() => {history.push('/')}}>
    BandMate
  </h1>
));

问题是在解构时,你想要 destructure props 但你没有将任何名为 props 的道具传递给 LogoName 组件

您可以将论点更改为

const LogoName = withRouter((props) => (
  <h1
    {...props}
    onClick={() => {props.history.push('/')}}>
    BandMate
  </h1>
));

但是,您仍然可以像@Danny 一样通过使用展开运算符语法来解构道具,例如

const LogoName = withRouter(({history, ...props}) => (
  <h1
    {...props}
    onClick={() => {history.push('/')}}>
    BandMate
  </h1>
));

这对我有用:

import  {withRouter} from 'react-router-dom';
class Login extends React.Component
{
   handleClick=()=>{
      this.props.history.push('/page');
   }
   render()
  {
     return(
          <div>
          .......
            <button onClick={this.handleClick()}>Redirect</button>
          </div>);
  }
}

export default withRouter(({history})=>{
  const classes = useStyles();
    return (
        <Login  history={history} classes={classes} />
    )
});