【问题标题】:Adding child components in react在反应中添加子组件
【发布时间】:2021-04-21 18:56:26
【问题描述】:

我想在Wrapper 组件的demo 元素中添加子元素

function Wrapper() {
    return (
        <div className="demo">Something</div>
    )
}
<Wrapper>
    <span>This is something</span>
</Wrapper>

但这不起作用! 这样做的正确方法是什么?

【问题讨论】:

  • demo 元素在哪里?

标签: javascript reactjs components jsx


【解决方案1】:

您可以使用children prop 来做到这一点

function Wrapper({children}) {
    return (
        <div className="demo">{children}</div>
    )
}

【讨论】:

    【解决方案2】:

    简单的方法是拨打{props.children}

    function Wrapper(props) {
      return (
          <div className="demo">{props.children}</div>
      )
    }
    ReactDOM.render(
      <Wrapper>
          <span>This is something</span>
      </Wrapper>
    , document.getElementById('root'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    
    <div id="root" ></div>

    从@Soroush Chehresa 对What is {this.props.children} and when you should use it? 的回答中说:

    this.props.children 的作用是它被用来显示你想要的任何东西 调用组件时在开始标签和结束标签之间包含

    【讨论】:

      【解决方案3】:

      将您的包装器组件更改为:

      function Wrapper({ children }) {
        return (
          <>
            <div className="demo">Something</div>
            {children}
          </>
        );
      }
      

      【讨论】:

        【解决方案4】:

        就像在你的包装函数中一样,只需添加子作为参数,因为包装函数需要消耗一些东西来为你提供一些东西,所以只需将子传递给包装函数,它在内部呈现你的子作为参数传递

        function Wrapper({children}) {
            return (
                <div className="demo">{children}</div>
            )
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-12-14
          • 2019-01-07
          • 1970-01-01
          • 2019-11-11
          • 2017-01-12
          • 1970-01-01
          • 2021-11-08
          • 2022-07-06
          相关资源
          最近更新 更多