繁体   English   中英

在不使用 this.props.children 的情况下将 components/JSX 作为 prop 传递给子组件

[英]Passing components/JSX as a prop to the child component without using this.props.children

我正在尝试创建一个帮助器组件来帮助我检查用户是否有权执行某个操作。 这个帮助器组件称为PermissionsChecker ,它将包裹感兴趣的 JSX。

我现在面临的问题是,如果检查失败,我希望能够指定一些要呈现的 JSX,例如,一些包含未经授权的文本的 jsx。

下面是进一步说明问题的代码:

class PermissionsChecker extends Component {
    checkperms(){
       //code which checks the user's permissions list
    }
    
    render() {
        if(this.checkperms() === true){
        return (
            this.props.children //<-- i will return whatever JSX it was wrapping.
            )}
        else{
        return(
            (this.props.replacement?
                <Fragment>
               {this.props.replacement}  //<--- here is where i wish to return the JSX if check fails
                </Fragment>
            )
        )
        }
    }
}

这是帮助程序 function 的操作:

<PermissionsChecker
   codeNames={['view_salesprojec2t']}
   replacement={<Text>{id}</Text>} >
   <Link to={`/project/detail/${id}`}>
   {id}
   </Link>
</PermissionsChecker>

正如你所看到的, this.props.children对我来说不是一个解决方案,因为我已经在利用它来返回原始 JSX。 我想做的是添加在替换道具中指定 JSX 的能力,然后如果检查通过,则从我的PermissionsChecker组件返回它。

我试图控制台记录this.props.replacement并且我收到了这个:

{$$typeof: Symbol(react.element), key: null, ref: null, props: {…}, type: ƒ, …}
$$typeof: Symbol(react.element)
key: null
props:
children: 1
__proto__: Object
ref: null
type: ƒ Text(_a)
_owner: FiberNode {tag: 11, key: null, elementType: {…}, type: {…}, stateNode: null, …}
_store: {validated: false}
_self: CustomerDetail {props: {…}, context: {…}, refs: {…}, updater: {…}, _reactInternalFiber: FiberNode, …}
__proto__: Object

有什么好的解决方法吗?

通过 props 传递构造组件 ( <Component/> ) 是一种反模式。

相反,您应该在props.children上使用条件渲染,同时检查组件级别的条件(而不是使用PermissionsChecker ):

<>
  {checkPermissions() ? (
    <Link to={`/project/detail/${id}`}>{id}</Link>
  ) : (
    <Text>{id}</Text>
  )}
</>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM