簡體   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