我想在单击按钮后添加更多组件。您可以分享代码或想法以便我可以实施吗?如图所示,每次用户单击添加按钮时,都会添加一行/组件。
这是哪里state https://facebook.github.io/react-native/docs/state.html闪耀的,
例如:
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>
);
}
所以每次你点击按钮时,
- _handleAddButton 被调用
- 添加了新数据,更新为设置状态() https://facebook.github.io/react/docs/react-component.html#setstate
-
render() https://facebook.github.io/react/docs/react-component.html#render被触发。
- more
<MyComponent>
添加到视图并显示
===============
2017/8/3 编辑:
如果你想进一步删除<MyComponent>
, 道具key https://facebook.github.io/react/docs/lists-and-keys.html#keys应该得到照顾。这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>
);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)