如何在反应中将另一个道具添加到...道具
How to add another prop to ...props in react
我正在使用 react-router,我创建了一个 PrivateRoute 组件,如果通过身份验证则显示该组件,否则重定向到登录页面。
我想做的是在调用者指定的 prop 之上传递一个额外的 prop(身份验证)。
我似乎无法获得正确的语法,谷歌搜索“...props”没有显示任何文档。
这是我的代码:
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
this.state.authentication.authenticated() ? (
<Component authentication:{this.state.authentication} {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
);
那将是一个与其他道具一样的道具:
<Component
authentication={this.state.authentication}
{...props}
/>
我发现将它们放在不同的行中有助于轻松查看发生的情况。
此外,如果 {...props}
已经包含一个名为 authentication
的密钥,那么您可以通过将其放在以下位置来覆盖它:
const someProps = {
hello: 1
};
// this.props.hello will be 2
<Component
{...someProps}
hello={2}
/>
问题出在 authentication
prop 语法上。使用 =
而不是 :
<Component authentication={this.state.authentication} {...props}/>
我正在使用 react-router,我创建了一个 PrivateRoute 组件,如果通过身份验证则显示该组件,否则重定向到登录页面。
我想做的是在调用者指定的 prop 之上传递一个额外的 prop(身份验证)。
我似乎无法获得正确的语法,谷歌搜索“...props”没有显示任何文档。
这是我的代码:
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
this.state.authentication.authenticated() ? (
<Component authentication:{this.state.authentication} {...props}/>
) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
);
那将是一个与其他道具一样的道具:
<Component
authentication={this.state.authentication}
{...props}
/>
我发现将它们放在不同的行中有助于轻松查看发生的情况。
此外,如果 {...props}
已经包含一个名为 authentication
的密钥,那么您可以通过将其放在以下位置来覆盖它:
const someProps = {
hello: 1
};
// this.props.hello will be 2
<Component
{...someProps}
hello={2}
/>
问题出在 authentication
prop 语法上。使用 =
而不是 :
<Component authentication={this.state.authentication} {...props}/>