如何动态添加更多组件React Native [英] How To Add More component dynamically React Native

查看:281
本文介绍了如何动态添加更多组件React Native的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在单击按钮后添加更多组件.您可以分享代码或想法,以便我实施吗?如图所示,每当用户单击添加按钮时,将添加一行/组件.

I want to add more components after clicking on the button. Can you share code or an idea so that I can implement? As the image shows, every time when user click on the add button, one row / component will be added.

推荐答案

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>
    );
}

因此,每次您单击按钮时,

So every time you click the button,

  1. _handleAddButton被调用
  2. 添加了新数据,并使用 setState()
  3. render()被触发.
  4. 更多<MyComponent>已添加到查看并显示"中
  1. _handleAddButton get called
  2. a new data is added, update with setState()
  3. render() get triggered.
  4. more <MyComponent> added into View and show

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

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

2017/8/3

如果您想进一步删除<MyComponent>,请使用 key 应该得到照顾. key充当react框架的更改检测器,一个自动递增的密钥将适合您的情况.例如:

if you want to further delete <MyComponent>, the prop key should be taken care of. The key act as change detector for react framework, an auto-increment key would suit your case. example:

_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>
    );
}

这篇关于如何动态添加更多组件React Native的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆