2016-11-19 342 views
0

什麼是最好的簡單實現這個jQuery的方式fiddle只使用React而不使用jQuery或任何其他庫?我還沒有很好的ReactJS技能,並且想知道是否有辦法動態地創建和刪除元素。在按鈕上添加和刪除HTML元素點擊反應

我想創建一個

this.state = { "inputs": ["<input type="text" /><input type="checkbox" />"] } 

狀態變量數組添加時保存的HTML,給基於索引每一個獨特的密鑰,然後.MAP(),但我不確定是否有一個更簡單的方法來實現這一點,我不確定如何刪除每個元素。

想了解任何幫助或反饋,謝謝!

回答

5

這是一個「反應」的方式來做到這一點,我不是一個React專家,所以代碼可能會更好,會接受更正。

  • 是的,反應有更多的樣板代碼,因爲你不直接處理DOM,並且有更少的「魔術」,這意味着你有更多的控制權。
  • 國家應儘可能最小化,您只需保存純數據,其他裝飾性的東西讓組件來處理它們。
  • 取決於具體情況,您可能需要將組件分成兩個獨立的組件,並使用更多的道具。
  • ???更多建議?

const Row = function(props){ 
 
    const {checked, value, onChange, onChecked} = props; 
 
    return (
 
    <div> 
 
     <input 
 
     type="checkbox" 
 
     checked={checked} 
 
     onChange={onChecked} 
 
     /> 
 
     <input type ="text" value={value} onChange={onChange}/> 
 
    </div> 
 
); 
 
} 
 

 
class App extends React.Component { 
 
    constructor(props){ 
 
    super(props); 
 
    this.state = { 
 
     rows: [ 
 
     {value: 'row1', checked: false}, 
 
     {value: 'row2', checked: true}, 
 
     {value: 'row3', checked: false}, 
 
     ] 
 
    }; 
 
    } 
 
    
 
    updateValue(e, idx){ 
 
    const rows = this.state.rows; 
 
    rows[idx].value = e.target.value; 
 
    this.setState({ 
 
     rows, 
 
    }); 
 
    } 
 
    
 
    onChecked(idx){ 
 
    const rows = this.state.rows; 
 
    rows[idx].checked = !rows[idx].checked; 
 
    this.setState({ 
 
     rows, 
 
    }); 
 
    } 
 
    
 
    addRow(){ 
 
    const rows = [...this.state.rows, 
 
        {value:'', checked: false} 
 
       ]; 
 
    this.setState({ 
 
     rows, 
 
    }); 
 
    } 
 
    
 
    deleteRows(){ 
 
    this.setState({ 
 
     rows: this.state.rows.filter((e, i) => !e.checked) 
 
    }); 
 
    } 
 
    
 
    render(){ 
 
    return(
 
     <div> 
 
     {this.state.rows.map((row, idx) => { 
 
      return(
 
       <Row 
 
       key={idx} 
 
       value={row.value} 
 
       checked={row.checked} 
 
       onChange={(e) => this.updateValue(e,idx)} 
 
       onChecked={() => this.onChecked(idx)} 
 
       /> 
 
      ) 
 
     }) 
 
     } 
 
     <button onClick={()=>this.addRow()}> 
 
      add 
 
     </button> 
 
     <button onClick={()=>this.deleteRows()}> 
 
      delete 
 
     </button> 
 
     </div> 
 
    ); 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    <App />, 
 
    document.getElementById('app') 
 
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 

 
<div id="app"> </div>