2

我一直試圖圍繞這個問題繞過我的頭一段時間。我一起黑了一個解決方案,直到我得到任何嵌套的div,然後事情崩潰。基本上我想要做的是創建合成組件,生活在更高階的組件中,並且都共享相同的當前狀態。然後我需要導出,以便任何文件都可以使用這些組件。因此,這裏的JSX可能是什麼樣子:反應:高級組件內的嵌套可重用組成組件

<Panel countersStartAt=5> 
    <Counter incrementsBy=1 /> 
    <div> 
    <Counter incrementsBy=2 /> 
    </div> 
    <TotalCounter className="someclass" /> 
</Panel> 

所以我想是這樣的工作的方式是,我有一個設置了一些初始狀態這個包裝面板組件,說this.state.start = 5.在面板中,一個Counter組件會有一個onClick處理程序,它通過incrementBy增加state.start。 TotalCounter將是一個顯示state.start的組件。當然這是一個人爲的例子,所以不要提出如何讓這個特定的組件變得更好。我正在尋求將此應用於更現實的情況。

第二件事是如何導出這些組件,以便我可以在無狀態組件中的獨立文件中創建上述確切代碼。希望這是有道理的。

這是我正在做的一個片段,以實現這一點。

renderChildren = (children) => { 
    return React.Children.map(children, (child) => { 
     if (React.isValidElement(child)) { 
     return React.createElement(
      (child.type.name ? this[child.type.name] : child.type), 
      child.props 
     ); 
     } 
     return child; 
    }); 
    }; 

    render =() => { 
    return (
     {this.renderChildren(this.props.children)} 
    ) 
    }; 

然後Panel類之外,我出口像這樣:

export const Counter =() => null;

正是如此它暴露計數器。默認的null渲染不會發生,因爲我使用Panel中的this.Counter()方法替換Counter。

問題的評論和其他的事情問

  • 我不使用助焊劑或終極版
  • 考慮假設面板的代碼片段被用在一些渲染跨不實施的幾個項目的方法通量模式或Redux
  • 假設那些代碼片段不能被重寫
  • 如何導出Panel,Counter和TotalCounter? Counter和TotalCounter是否可以這樣做,因爲它們是Panel類中的方法?我的研究導致「否」,並創建「虛擬」組件以導出,以便當前文件可以無誤地使用它們。
+0

您使用的是磁通店? – ryudice

+0

你問如何實現你想要的?又名面板? –

+0

@JohnRuddell是的,抱歉不清楚。我已經實現了它,但使用了一個類Panel和其他組件。然後,當我使用Panel I時,只需映射所有孩子並設置狀態等,但這絕對不是正確的解決方案。 – Nate

回答

1

就擺在這裏的答案是什麼,我們在聊天室

談到來處理你想不喜歡終極版或流量數據管理框架做的就是將您的數據什麼是最好的方式道具穿過,像這樣。

class Panel extends Component { 

    constructor(){ 
     super() 
     this.state = {count: 5} 
    } 
    incrementCount = (incrementer) => { 
     this.setState({count: this.state.count + incrementer}); 
    } 
    render(){ 
     return (
     <div> 
      <Counter incrementCount={this.incrementCount} count={this.state.count} incrementsBy=2 /> 
     </div> 
    ); 
    } 

} 

然後在櫃檯..

<someElement onClick={ (e) => {this.props.incrementCount(this.props.incrementsBy)} }>{this.props.count}</someElement>