簡體   English   中英

如何使用反應中的刪除按鈕從列表中刪除項目?

[英]how to delete item from list using delete button in react?

我正在使用add button生成一個動態列表。我能夠生成該動態列表。但是每個li也存在delete按鈕。我想在按下刪除按鈕時刪除該項目。我還要執行一個action redux。首先我不知道如何將點擊事件綁定到動態生成的列表上,當用戶按下刪除按鈕時出現錯誤

這是我的代碼https://plnkr.co/edit/JEG6o4JCBIQWAt2A4S3r?p=preview //代碼在這里

const { createStore, bindActionCreators, applyMiddleware,combineReducers } = Redux;
const { Provider, connect } = ReactRedux;
const thunk = window.ReduxThunk.default;


const first_redux =function(state =[] ,action){
  switch (action.type){
    case 'ADD_ITEM':
     return [
        ...state,
        action.payload
      ];
      case 'DELETE_ITEM':
      var index = state.indexOf(action.payload);
     return state.slice(index,1);
    default :
    return state

  }
}

const actions ={
 addItem :function(item){
  return {
    type :"ADD_ITEM",
    payload :item
  } 
 } ,
 deleteItem :function(item){
  return {
    type :"DELETE_ITEM",
    payload :item
  } 
 } 

}
var combindReducer = combineReducers({
  item:first_redux
})

const store = createStore(combindReducer);

class First extends React.Component {
  constructor (props){
    super(props);
    this.state = {
      names :[],
      username :''
    }
   this.changeEv =this.changeEv.bind(this);
   this.addName =this.addName.bind(this);
   this.handle =this.handle.bind(this);

  }
  changeEv(e){
    this.setState({
      username : e.target.value
    })
  }
  addName(){
    if(this.state.username !== ''){
    this.props.add(this.state.username)
     this.setState({
      username : ''
    })
    }
  }
  handle(){
    alert('---')
  }

  render() {
    const data =[{"name":"test1"},{"name":"test2"}];
    var listItems = this.props.names.map(function(d, idx){
      return (<li key={idx}><span>{d}</span><button onClick={this.handle}>delete</button></li>)
    })
    return (
      <div>
      <input type="text" onChange ={this.changeEv} value={this.state.username}/>
      <button onClick={this.addName}>add</button>
      {listItems}
      </div>
    );
  }
} 

function mapStateToProps(state){
  console.log('=================');
  console.log(state);
  return {
       names: state.item,

  };
    console.log(this.state);

}

function mapDispatchToProps(dispatch){
  return {
    add:bindActionCreators(actions.addItem,dispatch)
  }
}
const Appcontainer =connect(mapStateToProps,mapDispatchToProps)(First)

ReactDOM.render(
  <Provider store ={store}>
    <Appcontainer/>
    </Provider>
  ,document.getElementById('root'));

問題:

您在刪除按鈕得到一個錯誤,因為你正試圖將this.props.names.map內部訪問,這是不是組件的這一點。

解決方案

var listItems = this.props.names.map((d, idx) => {
  return (<li key={idx}><span>{d}</span><button onClick={this.handle}>delete</button></li>)
})

由於使用的是ES6,因此可以使用提供詞法作用域的箭頭功能 我已經更新了您的代碼。 在這里查看

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM