代码之家  ›  专栏  ›  技术社区  ›  Jeff

无法使用{}将图像作为属性传递。必须使用<>

  •  0
  • Jeff  · 技术社区  · 6 年前

    我有一个组件包含在我的站点上的一个部分(源代码在底部)。我在页面上包含了部分组件,

    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 回复  |  直到 6 年前
        1
  •  1
  •   bitsapien    6 年前

    这是一些非常整洁的重构。你应该试着去做,而不是让它工作。这是因为当你把一个组件作为道具传递时,它是没有状态的。它需要在内部实例化。

    第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