簡體   English   中英

將道具傳遞給包裝在 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傳遞給組件,我需要它來更改組件的類。 這里的問題是在<LogoName>組件中undefined props 當我單擊另一個組件時,我需要能夠更改此組件的類,如下所示:

<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-Router 導航並仍然接收道具的組件?

提前致謝。

問題是,在解構時,您想destructure props但沒有將任何名為props傳遞給LogoName組件

你可以改變你的論點

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

但是,您仍然可以通過使用擴展運算符語法(如

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

你很接近,只需在你的函數簽名中傳播道具:

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} />
    )
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM