回答

7

這也正是state照耀下,

例如:

constructor(props) { 
    super(props); 

    this._handleAddButton = this._handleAddButton.bind(this); 

    this.state = { /* initial your state. without any added component */ 
     data: [] 
    } 
} 

_handleAddButton() { 
    let newly_added_data = { title: 'new title', content: 'new content goes here' }; 

    this.setState({ 
     data: [...this.state.data, newly_added_data] 
    }); 
} 

render() { 
    let added_buttons_goes_here = this.state.data.map((data, index) => { 
     return (
      <MyComponent key={index} pass_in_data={data} /> 
     ) 
    }); 

    return (
     <View> 
      <Button title="Add more" onPress={this._handleAddButton} /> 
      {added_buttons_goes_here} 
     </View> 
    ); 
} 

所以每次單擊該按鈕,

  1. _handleAddButton得到所謂
  2. 新數據補充,更新爲setState()
  3. render()被觸發。
  4. <MyComponent>加入搜索並顯示

================

2017年8月3日編輯:

,如果你想要進一步刪除<MyComponent>,應該照顧道具keykey作爲響應框架的變化檢測器,一個自動遞增的密鑰將適合您的情況。例如:

_handleAddButton() { 
    let newly_added_data = { 
     /* psedo code to simulate key auto increment */ 
     key: this.state.data[this.state.data.length-1].key+1, 
     title: 'new title', 
     content: 'new content goes here' 
    }; 

    this.setState({ 
     data: [...this.state.data, newly_added_data] 
    }); 
} 

_handleRemoveButton(key) { 
    let result = this.state.data.filter((data) => data.key !== key); 

    this.setState({ 
     data: result, 
    }); 
} 

render() { 
    let added_buttons_goes_here = this.state.data.map((data, index) => { 
     return (
      <MyComponent key={data.key} pass_in_data={data}> 
       /// psedo code of pass-in remove button as a children 
       <Button title="Remove" onPress={() => this._handleRemoveButton(data.key) } /> 
      </MyComponent> 
     ) 
    }); 

    return (
     <View> 
      <Button title="Add more" onPress={this._handleAddButton} /> 
      {added_buttons_goes_here} 
     </View> 
    ); 
} 
+0

並且想要刪除MyComponent。它如何.. –

+0

修改我的答案與代碼刪除。 – Val

+0

好的我將在我的代碼中實現。 –