2
我想單擊按鈕後添加更多的組件。你可以分享代碼或想法,以便我可以實施?如圖所示,每次用戶點擊添加按鈕時,都會添加一行/組件。如何動態添加更多組件反應本機
我想單擊按鈕後添加更多的組件。你可以分享代碼或想法,以便我可以實施?如圖所示,每次用戶點擊添加按鈕時,都會添加一行/組件。如何動態添加更多組件反應本機
這也正是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>
);
}
所以每次單擊該按鈕,
<MyComponent>
加入搜索並顯示================
2017年8月3日編輯:
,如果你想要進一步刪除<MyComponent>
,應該照顧道具key
。 key
作爲響應框架的變化檢測器,一個自動遞增的密鑰將適合您的情況。例如:
_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>
);
}
並且想要刪除MyComponent。它如何.. –
修改我的答案與代碼刪除。 – Val
好的我將在我的代碼中實現。 –