2016-06-13 61 views
2

我看到這個錯誤在我的控制檯:爲什麼React說「無效的道具`兒童`」?

警告:無法propType:提供給ButtonRow無效道具children。檢查BookingForm的渲染方法。

ButtonRow看起來是這樣的:

import React, {Component, PropTypes} from 'react'; 

export function Left(props) { 
    return <div className="left-col">{props.children}</div>; 
} 

export function Right(props) { 
    return <div className="right-col">{props.children}</div>; 
} 

const LeftOrRight = PropTypes.oneOfType([Left, Right]); 

export default class ButtonRow extends Component { 
    static propTypes = { 
     children: PropTypes.oneOfType([ 
      PropTypes.arrayOf(LeftOrRight), 
      LeftOrRight, 
     ]).isRequired, 
    }; 

    render() { 
     console.log(this.props.children); 
     let children = React.Children.toArray(this.props.children); 
     return <div className="row"> 
      {children.filter(c => c.type === Left)} 
      {children.filter(c => c.type === Right)} 
     </div> 
    } 
} 

ButtonRow.Left = Left; 
ButtonRow.Right = Right; 

而我渲染這樣的:

<ButtonRow> 
    <ButtonRow.Left> 
     xxx 
    </ButtonRow.Left> 
    <ButtonRow.Right> 
     yyy 
    </ButtonRow.Right> 
</ButtonRow> 

它顯示正是我所期待。如何驗證失敗?我應該如何設置propTypes

理想情況下,我想執行的一個:

  • 一個Left孩子
  • 一個Right孩子
  • 一個Left和一個Right

閒來無事應該接受

+0

只是退後一步。你的左和右無狀態函數有什麼好處呢?含義。它們是相同的。爲什麼他們都擁有他們?爲什麼不只有一個呈現相同的東西?看起來這是過於複雜。 –

+1

@JohnRuddell尚未完成寫作;它們在一秒之內會有所不同;) – mpen

+0

您可以在發出警告的行上放置一個斷點,並使用調用堆棧來查找proptypes驗證失敗的確切位置。再次使用 – zerkms

回答

1

你可以crea TE定製的可重複使用的道具類型是這樣的:

export function childrenOf(...types) { 
    let fieldType = PropTypes.shape({ 
     type: PropTypes.oneOf(types).isRequired, 
    }); 

    return PropTypes.oneOfType([ 
     fieldType, 
     PropTypes.arrayOf(fieldType), 
    ]); 
} 

,然後用它是這樣的:

export default class RadioMenu extends React.Component { 

    static propTypes = { 
     children: WxTypes.childrenOf(RadioButton).isRequired, 
    }; 

    ... 
} 
1

這個答案是正確的https://stackoverflow.com/a/41992473/1426788,但我想用同樣分享我的經驗問題。發生

這個錯誤對我來說,當我在我的包裝成分,使一個孩子,而不是多個:

例如:

<Foo> 
    <Bar> 
</Foo> 

會拋出一個警告,其中

<Foo> 
    <Bar> 
    <Baz> 
</Foo> 

不會。

似乎呈現單個孩子的反應遵循不同的語義,然後呈現多個孩子和PropTypes應相應地更新。

在這裏可以PropTypes更多信息:https://facebook.github.io/react/docs/typechecking-with-proptypes.html#proptypes

+0

這不是這種情況。問題是'oneOfType'需要另一個PropType,而不是React組件類作爲參數。 – mpen

+0

正確的我打算傳達一個觸發我自己警告的場景。你的回答是正確的,我正在增加與另一場景的對話,以便人們使用相同的警告。讓我更新我的回覆 – lfender6445

+0

啊,好吧。很公平 :-) – mpen