将项目数据传递给react模式 [英] Pass item data to a react modal

查看:70
本文介绍了将项目数据传递给react模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张地图可以呈现少量商品,其中一行在下面

I have a map that render few items and one of its line is below

<a onClick={()=> this.setState({"openDeleteModal":true)}>Delete</a>

显然我想在用户点击删除时打开一个模态,但我必须传递一些东西喜欢项目的名称,执行删除的项目的ID。我如何通过将名称传给模态?

Obviously I want to open a modal when user click the delete, but I have to pass a few things like the name of the item, id of the item to perform the deletion. How can I pass says the name to the modal?

我可以将obj名称绑定到 a 这样的
删除

I can bind the obj name to a like this Delete

我是否走在正确的轨道上?

Am I on the right track?

推荐答案

在处理React应用程序时,尽量不要考虑将值传递给其他组件,而是更新组件所暴露的状态。
在您的示例中,假设您的模态组件是 a 标记列表所属的同一组件的子组件,您可以设置您感兴趣的值到状态的模态,以及更新信号是否打开模态的属性。例如:

When working on React applications, try not to think in terms of passing values to other components, but rather updating state that your components are exposed to. In your example, assuming your modal component is a child of the same component your list of a tags belongs to, you could set the values you are interested in exposing to the modal on the state, as well as updating the property that signals whether the modal is open or not. For example:

class Container extends React.Component {
    constructor(props) {
       super(props)
       this.state = {
          openDeleteModal: false,
          activeItemName: '', //state property to hold item name
          activeItemId: null, //state property to hold item id
       }
    }

    openModalWithItem(item) {
       this.setState({
          openDeleteModal: true,
          activeItemName: item.name,
          activeItemId: item.id
       })
    }

    render() {

    let buttonList = this.props.item.map( item => {
      return (<button onClick={() => this.openModalWithItem(item)}>{item.name}</button>
    });

    return (
     <div>
        {/* Example Modal Component */}
        <Modal isOpen={this.state.openDeleteModal}  
               itemId={this.state.activeItemId}
               itemName={this.state.activeItemName}/>
        { buttonList }
     </div>
    )
    }
}

这篇关于将项目数据传递给react模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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