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
好的我将在我的代码中实现。 –