盖茨比2.4.11
我有一个组件在我的网站上体现了一个部分(底部的源代码)。我在页面上包含了Section组件,
import SomeIcon from '../images/icons/something.svg'
const SomePage = () => (
<Section title="Lorum Ipsum" icon=<SomeIcon/>>
<p>Lorum ipsum dolor sit amet</p>
</Section>
)
这可以正常显示页面。但是,该语法icon=<SomeIcon/>
深深地触犯了我的核心。另外,它还破坏了文本编辑器的语法检查器和语法颜色。我想将其切换为{}
<Section title="Lorum Ipsum" icon={SomeIcon}>
但是使用此语法,图标不会呈现。它只是空白。如何将图像作为带有花键{}
的属性传递?
import React from 'react'
import PropTypes from 'prop-types'
const Section = ({ children, icon, title, background, fullWidth }) => (
<section style={{background:background}}>
<div class="wrap">
<h2>{title}</h2>
<span class="icon">{icon}</span>
<div class="content">
{children}
</div>
</div>
</section>
)
Section.propTypes = {
title: PropTypes.string,
icon: PropTypes.string,
background: PropTypes.string,
fullWidth: PropTypes.boolean,
}
Section.defaultProps = {
title: ``,
icon: ``,
background: ``,
fullWidth: false,
}
export default Section
答案 0 :(得分:1)
那是相当整洁的重构。您可能应该尝试执行此操作以使其起作用。这是因为当您将组件作为道具传递时,它没有被实例化。需要在内部实例化。
Section.js
import React from 'react'
import PropTypes from 'prop-types'
const Section = ({ children, icon, title, background, fullWidth }) => (
<section style={{background:background}}>
<div class="wrap">
<h2>{title}</h2>
<span class="icon">{icon()}</span> {/* Notice this line */}
<div class="content">
{children}
</div>
</div>
</section>
)
Section.propTypes = {
title: PropTypes.string,
icon: PropTypes.func, // Notice this line
background: PropTypes.string,
fullWidth: PropTypes.boolean,
}
Section.defaultProps = {
title: ``,
icon: ``,
background: ``,
fullWidth: false,
}
export default Section