【问题标题】:Wrapping functional JSX components with other functions用其他功能包装功能性 JSX 组件
【发布时间】:2019-07-01 16:57:31
【问题描述】:

我想创建一个封装其他组件并在其渲染方法中使用 JSX 的功能组件。我在网上看到了很多关于如何使用类组件做到这一点的内容,但我很好奇它是否适用于功能组件。

function WrappedContent() {
  return <p>I'm wrapped</p>
}

function Wrapper(WrappedComponent) {
  return (
    <div>
      <p>Wrapped: </p>
      <WrappedComponent />
    </div>
  )
};


function App() {
  return (
    <div>
      <Wrapper>
        <WrappedContent />
      </Wrapper>
    </div>
  )
}

我猜这与子组件如何传递到 &lt;Wrapper&gt;(通过 props.children?)有关。

这是一个包含上述代码的代码框:https://codesandbox.io/embed/gifted-cray-bqswi

【问题讨论】:

  • 下次注意,Stack Overflow 的 Stack Snippets 支持 React,包括 JSX; here's how to do one。使用现场 sn-ps 可以帮助人们帮助您。

标签: javascript reactjs


【解决方案1】:

(通过 props.children?)

是的:

function WrappedContent() {
  return <p>I'm wrapped</p>
}

function Wrapper(props) {
  return (
    <div>
      <p>Wrapped: </p>
      {props.children}
    </div>
  )
}

function App() {
  return (
    <div>
      <Wrapper>
        <WrappedContent />
      </Wrapper>
    </div>
  )
}

ReactDOM.render(<App/>, document.getElementById("root"));
<div id="root"></div>
<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>

注意Wrapper 接受一个名为props 的参数,并使用props.children。如果你没有任何其他道具(或者即使你有,但数量很少),你可以通过解构来做到这一点:

function Wrapper({children}) {
  return (
    <div>
      <p>Wrapped: </p>
      {children}
    </div>
  )
}

【讨论】:

  • 太好了,谢谢。如果我想向WrappedComponent 添加一个属性,例如onDoubleClickref
  • @labarna - 在Wrapper?您不会,在调用 Wrapper 之前已经创建了该元素。您需要在将其传递给 Wrapper 的组件中执行此操作。
  • 知道了,好吧,我得重新考虑一下我的机智...我正在尝试创建一个可编辑的 Wrapper,它显示一个输入(双击时),然后调用子组件来更新它的状态编辑后。
【解决方案2】:

传递给功能组件的是props,子元素包含在props.children中:

function WrappedContent() {
  return <p>I'm wrapped</p>
}

function Wrapper(props) { // <-- here
  return (
    <div>
      <p>Wrapped: </p>
      {props.children} // <-- here
    </div>
  )
};


function App() {
  return (
    <div>
      <Wrapper>
        <WrappedContent />
      </Wrapper>
    </div>
  )
}

https://codesandbox.io/embed/priceless-borg-brlbk

【讨论】:

    【解决方案3】:

    你可以试试这样的。

    function WrappedContent() {
      return <p>I'm wrapped</p>
    }
    
    function Wrapper(props) {
      return (
        <div>
          <p>Wrapped: </p>
          {props.children}
        </div>
      )
    };
    
    
    function App() {
      return (
        <div>
          <Wrapper>
            <WrappedContent />
          </Wrapper>
        </div>
      )
    }
    

    您可能还想参考这篇文章https://reactjs.org/docs/composition-vs-inheritance.html

    【讨论】: