简体   繁体   中英

Pass item data to a react modal

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

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

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?

I can bind the obj name to a like this Delete

Am I on the right track?

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

如果你给了更多的代码来更好地理解它会很好..从我的理解,你可以创建一个名为“selectedItem”的状态并将其设置为onClick ...然后在确认模态时,你可以从州传递所需的数据..

Copying over my answer from How to pass props to a modal

Similar scenario

constructor(props) {

    super(props)


    this.state = {
      isModalOpen: false,
      modalProduct: undefined,
    }
}

//****************************************************************************/

render() {

    return (
        <h4> Bag </h4>
        {this.state.isModalOpen & (
          <Modal 
            modalProduct={this.state.modalProduct}
            closeModal={() => this.setState({ isModalOpen: false, modalProduct: undefined})
            deleteProduct={ ... }
          />
        )

        {bag.products.map((product, index) => (
        <div key={index}>
            <div>{product.name}</div>
            <div>£{product.price}</div>
            <div>
            <span> Quantity:{product.quantity} </span>
            <button onClick={() => this.props.incrementQuantity(product, product.quantity += 1)}> + </button>
            <button onClick={() => this.decrementQuantity(product)}> - </button> // <----
            </div>
        </div>
        ))}
    )
}

//****************************************************************************/

decrementQuantity(product) {

    if(product.quantity === 1) {
        this.setState({ isModalOpen: true, modalProduct: product })
    } else {
        this.props.decrementQuantity(product)
    }
}

Try this: this is the form which has the button, and is a child component of some other component that passes the handleButtonAction method as props, and the button takes the input data and invokes this parent component method

handleSubmit = (e) => {
  e.preventDefault();
  const data = e.target.elements.option.value.trim();
  if (!data) {
    this.setState(() => ({ error: 'Please type data' }));
  } else {
    this.props.handleButtonAction(data, date);
  }
} 

{this.state.error && <p>{this.state.error}</p>} 
<form onSubmit={this.handleSubmit}>
  <input type="text" name="option"/>
  <div>
    <button>Get data</button>
  </div>
</form>

The parent component:

handleButtonAction = (data) => {

  axios.get(`http://localhost:3000/someGetMethod/${data}`).then(response => {
        const resData = response.data;
        this.setState({
            openModal: true,
            status: response.status,
            data: resData
         });
    }).catch((error) => {
        if (error.message.toLowerCase() === 'network error') {              
          this.setStateWithError(-1, {});
        }
        else { // not found aka 404              
          this.setStateWithError(error.response.status, '', {currency, date: ddat});
        }
    });        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM