我想知道是否有辦法在陣列中創建元素然后簡單地渲染它們,如果可能的話,它會稍微簡化我的代碼。
現在我正在為一個檔案中的頁面定義部分,然后將其發送到另一個檔案等等,所以目前它看起來像這樣
const heroSectionProps = { ... }
const pageLayout = {
sections: [{name: "Hero", props: heroSectionProps}]
}
稍后在渲染頁面時,我正在執行以下操作:
import { Hero } from "~/sections"
const section = {
Hero: Hero
}
export const Page = ({ sections, ...props }) => {
return sections.map(({ name, props }) => {
const Section = section[name];
return <Section {...props} />
})
}
這作業得很好,現在的問題是,是否有可能以某種方式轉移到看起來更像這樣的語法:
import { Hero } from "~/sections"
const heroSectionProps = { ... }
const pageLayout = {
sections: [Hero(heroSectionProps)]
}
然后在頁面中:
export const Page = ({ sections, ...props }) => {
return sections.map(Section => (<Section />))
}
所以想法是已經在布局物件中創建了組件,然后簡單地將它們傳遞給頁面以直接呈現它們。當然,按照上面的方法做,我得到了一個錯誤:
Warning: React.jsx: type is invalid -- expected a
string (for built-in components) or a class/function (for composite components) but got: <HeroContainer />. Did you accidentally export a JSX literal
instead of a component?
和其他類似的關于無效型別。
那么這是否可能,值得嗎?
uj5u.com熱心網友回復:
你可以渲染一個陣列,只要它填充了可渲染的值(字串、數字、元素和組件)。所以,假設我們有一個組件陣列:
import Hero from '../Hero';
const componentsArray = [<p>Hello world!</p>, <div><img src="images/flower.png" /></div>, <Hero {...heroSectionProps} />];
您可以立即渲染它:
const Component = (props) => {
//...
return componentsArray;
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/344937.html
標籤:反应
上一篇:在本機反應中移動到下一個螢屏
