簡體   English   中英

reactjs中組件內部的函數

[英]Function inside component in reactjs

我有以下代碼片段

return (
   <InputMask
         mask="99:99"
         *some other prop*
   >
    {(inputProps) => (
         <Input
            {...inputProps}
            onSubmit={*Does something*}
          />
   </InputMask>)

這是自定義組件的返回,我的問題是關於語法...如何在組件內定義函數? 每當呈現此組件時是否都會調用此函數? 傳入此函數的內容是什么(在這種情況下,InputProps 是如何傳入的以及它包含什么內容)?

正如您可以推斷出的,我對前端開發和一般反應都很陌生,因此任何對任何文檔的指導或參考都會有很大幫助!

所以首先是一個快速定義。 這是我使用兒童的一些 JSX:

<MyComponent>
   <b>
       This bold element
   </b>
   And this text are children of MyComponent.
</MyComponent>

MyComponent 內部是一個常規的渲染方法,除了重要的是,它還有一個props.children可以做任何它想做的事情:

render(){
   return <div className="my-component">{this.props.children}</div>;
}

重要的是,孩子只是一個道具,就像其他任何東西一樣 它可以是您想要的任何東西,包括函數。 如果組件想要向其未知子組件提供一些信息,這將特別強大。 一個很好的例子是某種迭代器:

<Loop over={[1,2,3]}>
   {item => <span>{item}</span>}
</Loop>

Loop 組件調用 this.children 的地方,因為它期望它是一個函數:

render(){

   // For each item in the 'over' prop, call this.props.children
   return this.props.over.map(this.props.children);

}

本質上,這就是你所擁有的——就該函數何時運行以及 inputProps 對象是什么而言,這完全取決於 InputMask 組件,但幾乎可以肯定的是,它會在呈現時運行它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM