[英]Wrapping functional JSX components with other functions
我想創建一個包裝其他組件並在其render方法中使用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>
)
}
我猜想這與子組件如何(通過props.children?)傳遞到<Wrapper>
。
這是帶有上面代碼的codeandbox: https ://codesandbox.io/embed/gifted-cray-bqswi
(通過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>
)
}
傳遞給功能組件的是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>
)
}
您可以嘗試這樣。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.