React JS为每个项添加删除按钮

时间:2017-11-20 16:41:15

标签: javascript reactjs redux react-redux

我目前在页面底部有一个按钮,按下第二个索引(位置1)时按下的项目,即James Johnson和George Brown。

但是我想将此按钮添加到列表中的每个项目,以便删除该索引处的项目。

实施例,

John Smith - 删除

James Johnson - 删除

George Brown - 删除

单击名称旁边的“删除”按钮将删除该项目。

friendsActions.js

import * as f from '../constants'

export const addFriend = ({ firstname, lastname }) => ({
  type: f.ADD_FRIEND,
  frienditem: {
    firstname,
    lastname,
  },  
})

export const removeFriend = ({ key }) => ({
   type: f.REMOVE_FRIEND,
  key,
})

friendsReducer.js

import * as f from '../constants'

const initialState = [
  { firstname: 'John', lastname: 'Smith' },
  { firstname: 'James', lastname: 'Johnson' },
  { firstname: 'George', lastname: 'Brown' },
 ]

const friendsReducer = (state = initialState, action) => {
  switch (action.type) {
    case f.ADD_FRIEND:
      return [...state, action.frienditem] 
    case f.REMOVE_FRIEND:
      console.log('removing friend with key ' + action.key)
      return [...state.slice(0, action.key), ...state.slice(action.key + 1)]
    default:
       return state
  }
 }

export default friendsReducer

index.js(常数)

export const ADD_FRIEND = 'ADD_FRIEND'
export const REMOVE_FRIEND = 'REMOVE_FRIEND'
friendsContainer.js

import React from 'react'
import Page from '../components/Page'

import FriendList from '../containers/FriendList'

import { css } from 'glamor'

const FriendContainer = props => (
  <Page title="Friends List" colour="blue">
    <FriendList {...props} />
  </Page>
)

export default FriendContainer

friendsList.js

import React from 'react'
import { css } from 'glamor'

const Friend = ({ firstname, lastname }) => (
  <div>
    <ul>
      <li>
        {firstname} {lastname}
      </li>
    </ul>
  </div>
)

const FriendList = ({ friends, addFriend, removeFriend }) => (
  <div>
    <div>
      {friends.map((frn, i) => (
        <Friend key={++i} firstname={frn.firstname} lastname={frn.lastname} />
      ))}
    </div>
    <button onClick={() => addFriend({ firstname: 'New', lastname: 'Friend' })}>
      Add Friend
    </button>
    <button onClick={() => removeFriend({ key: 1 })}>Remove Friend</button>
  </div>
)

export default FriendList

1 个答案:

答案 0 :(得分:0)

在friendList.js

const FriendList = ({ friends, addFriend, removeFriend }) => (
  <div>
    <div>
      {friends.map((frn, i) => (
        <div key={i}>
           <Friend firstname={frn.firstname} lastname={frn.lastname} />
           /* with some styling */
           <button onClick={() => removeFriend({ key: i })}>Remove Friend</button>
        </div> 
      ))}
    </div>
    <button onClick={() => addFriend({ firstname: 'New', lastname: 'Friend' })}>
      Add Friend
    </button>
  </div>
)