【问题标题】:Is it possible to put a component inside a component?是否可以将组件放入组件中?
【发布时间】:2021-08-03 15:40:08
【问题描述】:

我已经制作了一个我想要重用的Form 组件,我还制作了一个我想要重用的Submit 组件。是否可以将Submit 组件放在Form 组件中?

export const Form = () => {
    return (
        <form>
            
        </form>
    )
}

提交.js

export const Submit = () => {
    return (
        <>
           <input type="submit">
        </>
    )
}

测验.js

export const Quiz = () => {
    return (
        <Form>
            <Submit>
        </Form>
    )
}

【问题讨论】:

标签: javascript html reactjs ecmascript-6 react-component


【解决方案1】:

是的,您需要添加参数“props”来形成组件并在显示 {props.children} 上输出:

const Form = (props) => {
  return (
      <form>
          {props.children}
      </form>
  )
}

CodeSanbox demo

【讨论】:

    【解决方案2】:

    您可以使用children prop 来实现此目的。

    基本上,在您的 Form.js 中,使用 props.children

    export const Form = (props) => {
        return (
            <form>
                {props.children}
            </form>
        )
    }
    

    然后在你的Quiz.js,像这样使用它。

    export const Quiz = () => {
        return (
            <Form>
               <Submit />
            </Form>
        )
    }
    

    &lt;Submit /&gt; 组件现在将在您的 Form 组件中呈现

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-19
    • 1970-01-01
    • 1970-01-01
    • 2010-11-30
    • 2017-04-01
    • 1970-01-01
    • 2015-12-27
    • 1970-01-01
    相关资源
    最近更新 更多