2016-05-15 37 views
0

完成此操作的React方式是什麼?按下按鈕時刪除選中的項目

我應該將複選框設置爲子組件嗎? - >如何將刪除事件傳遞給子組件?

如果我不設置複選框爲子組件將我的每個項目需要一個for循環中循環,並檢查它是否是檢查,如果爲true,則刪除

我敢肯定有一個優雅的解決方案但我對React很陌生,我還沒有理解這些概念 - 所以如果有任何額外的閱讀可以幫助提高我的理解,那麼請讓我知道!

回答

0

我現在可以想到的最簡單的方法是擁有一個包含複選框(或至少複選框狀態)數組的組件。該組件將顯示覆選框以及一個按鈕,點擊該按鈕將迭代該數組並刪除所有選中的框。

如果您不想將所有內容都保存在一個組件中,有多種方法可以實現此目的。例如,您可以輕鬆地將按鈕和複選框數組保留在父組件中,並將數組作爲通道傳遞給子組件。

您可能想看看flux,這是一種處理您的應用程序狀態(複選框數組)的方法。流量的流行實現是redux

您也可以使用React without flux(如上所示),這裏有一篇關於8 no-flux stragergies for react component communication的文章。

0

基本上,父組件會跟蹤子列表以及要刪除的子列表。每選中一個複選框,它都被添加到刪除列表中,並且如果未選中,則從刪除列表中刪除。當點擊刪除按鈕時,刪除列表中的每個項目都將從子列表中刪除,刪除列表將被清除,並調用setState來重新呈現組件。

import React from 'react'; 
import ReactDOM from 'react-dom'; 

class Form extends React.Component { 
    constructor(props) { 
    super(props) 
    } 
    // A delete-list and a list of children. 
    state = { 
    toDel: [], 
    checks: [] 
    } 
    // Method called when checkbox is clicked. 
    recId = (idToDel) => { 
    // Grab the checkbox that was clicked. 
    let checker = document.getElementById(idToDel); 
    if (checker.checked) { 
     // Add the id to delete-list. 
     this.state.toDel.push(idToDel); 
    } 
    else { 
     // Remove the id from delete-list. 
     let index = this.state.toDel.indexOf(idToDel); 
     this.state.toDel.splice(index, 1); 
    } 
    } 
    // Method called when delete button is clicked. 
    del =() => { 
    // Loop through items to delete. 
    for (var i = 0; i < this.state.toDel.length; i++) { 
     // Convert id from string back to integer. 
     let index = parseInt(this.state.toDel[i]) 
     // Replace the item to delete with empty string, so that every 
     // other element remains in place. 
     this.state.checks[index] = ''; 
    } 
    // Re-render the component by calling setState. 
    this.setState({ 
     toDel: [], 
     checks: this.state.checks 
    }); 
    } 
    // Loading the component with child checkboxes. Children are handed 
    // parent methods as event handlers. 
    componentWillMount =() => { 
    for (var i = 0; i < 5; i++) { 
     this.state.checks.push(
     <p key={i}> 
      <Check id={i.toString()} record={this.recId} />{i.toString()} 
     </p> 
    ) 
    } 
    } 
    render() { 
    return (
     <div> 
     {this.state.checks} 
     <button onClick={this.del}>Delete</button> 
     </div> 
    ); 
    } 
} 

class Check extends React.Component { 
    constructor(props) { 
    super(props) 
    } 
    state = {} 
    render =() => { 
    // Call the parent method on click with proper context and pass 
    // id of this specific child back up to parent. 
    return (
     <input type='checkbox' onClick={this.props.record.bind(null, this.props.id)} id={this.props.id} /> 
    ); 
    } 
} 

// Render component. 
ReactDOM.render(
    <Form />, 
    document.getElementById('test-container') 
); 
相關問題