[英]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.