[英]“Objects are not valid as a React child. If you meant to render a collection of children, use an array instead.” error
[英]Objects are not valid as a React child. If you meant to render a collection of children, use an array instead. How to return it?
根據我一直在閱讀的內容,錯誤是通過嘗試打印“{menu.props.options[0]}”產生的。 我知道我不能像這樣返回它,因為我必須將它包裝在 object 或數組中。
有問題的代碼是:
return (
<Select
labelInValue
filterOption={ false }
showArrow
suffixIcon={ <SearchOutlined /> }
onSearch={ debounceFetcher }
notFoundContent={ fetching ? <Spin size="small" /> : null }
{ ...props }
className="search-repeated-words"
dropdownRender={menu => (
<div>
{menu.props.options[0]}
<div style={{ padding: "0 12px", height: 30, lineHeight: "30px", color: "#46C4C1" }} >
Sugerencias
</div>
<Divider style={{ margin: 5 }} />
{menu}
</div>
)}
>
{
options.map((option, index) => (
<Select.Option key={index} value={option.text}>
<span>{option.text}</span>
</Select.Option>
)
)
}
</Select>
我可以實施什么解決方案?
menu.props.options[0] = object:
當我想在屏幕上打印或顯示 {menu.props.options[0]} 時會產生錯誤。 我怎么能顯示它?
我猜{menu.props.options[0]}
是一個 object。你應該只顯示這個 object 的相關屬性,具有基本類型(例如字符串),例如menu.props?.options?.[0]?.label
如果錯誤是通過嘗試渲染產生的
{menu.props.options[0]}
那么這意味着 menu.props.option[0] 是一個 Object 類型,你應該像這樣渲染它
<div>{menu.props.options[0].title} {menu.props.options[0].description}</div>
(取決於 object 包含哪些屬性)
或者,如果您出於某種原因想要按原樣呈現 object:
<div>{ JSON.stringify(menu.props.options[0]) }</div>
創建一個可以呈現option
數據的助手 function(或另一個組件)。 下面我創建了一個標記為OptionCell
的標簽,用於呈現第一個元素以及整個選項數組:
const OptionCell = (option) => ( <Select.Option key={index} value={option.text}> <span>{option.text}</span> </Select.Option> ) return ( <Select labelInValue filterOption={ false } showArrow suffixIcon={ <SearchOutlined /> } onSearch={ debounceFetcher } notFoundContent={ fetching? <Spin size="small" />: null } {...props } className="search-repeated-words" dropdownRender={menu => ( <div> {<OptionCell options={menu.props.options[0]} />) <div style={{ padding: "0 12px", height: 30, lineHeight: "30px", color: "#46C4C1" }} > Sugerencias </div> <Divider style={{ margin: 5 }} /> {menu} </div> )} > { options.map((option, index) => ( <OptionCell options={options} key={index} /> ) } </Select> )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.