jquery与react.js从列表中删除项目

jquery vs react.js remove item from a list

本文关键字:列表 删除项目 js react jquery      更新时间:2023-09-26

const RenderItem = (props) => {
    return(
      <ul id="todo">
      {props.items.map((item,i) => 
        <li className='list-group-item' data-id={item.id} key={i}>{item.name}
        <button className="btn btn-sm btn-primary" onClick={() => props.remove(item.id)}>X</button>
        </li>
      )}
      </ul>
    ) 
};
const TodoItems = React.createClass({
  getInitialState() {
    return {
      items: [
        {id:1,name:"Gym"},
        {id:2,name:"Jump"},
        {id:3,name:"Racing"}
      ]
    }
  },
  remove(id){
  this.setState({
  	items: this.state.items.filter((el) => id !== el.id)
  })
  },
  render(){
    return(
      <RenderItem items={this.state.items} remove={this.remove}/>
    ) 
  }
})
ReactDOM.render(
  <TodoItems />,
  document.getElementById('container')
);
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://npmcdn.com/react@latest/dist/react-with-addons.js"></script>
<script src="https://npmcdn.com/react-dom@latest/dist/react-dom.js"></script>
<div id="container">
    <!-- This element's contents will be replaced with your component. -->
</div>

我很困惑东西在这里是如何工作的.js,我需要presduo代码如何传递工作。我来自jquery背景,它非常简单,只需获得正确的dom并执行$(this(.remove((,而在反应中我很困惑。

<button className="btn btn-sm btn-primary" onClick={() => props.remove(item.id)}>X</button>

当你点击发生了什么?箭头功能? 删除从何而来?

React 遵循单向数据绑定,这意味着数据将沿单个方向流动。因此,数据存储在 state .每当state发生变化时,组件就会re-render .状态可以在任何时间点更改。但是,大多数情况下,它会在任何action上更改。在您的情况下,onClick()中的操作.这将调用该函数将触发onClick()的元素的id。现在,在该函数中,您将遍历state,使用setState()识别、删除和设置新状态,这将使用新数据重新渲染组件。此渲染将没有单击的元素,因为它已从状态中删除。

remove()函数从父组件传递到子组件,可以使用props访问。这将是对父组件中声明的函数的引用。在单击期间,使用此引用,将调用父组件中的函数!

在 react 中,组件根据它们的propsstate进行渲染。 props是从父组件传递的,组件可能有也可能没有内部state

使用 jQuery,您将尝试通过直接删除 DOM 节点来删除它。然而,在 React 中,直接与 DOM 交互是一种反模式。由于当前stateprops决定了渲染的内容,因此您希望更改其中一个将导致重新渲染并显示新内容的内容。

在您的情况下,您似乎正在尝试直接修改propsprops是只读的,不应修改。由于props是从父组件传递下来的,因此您必须更改从父组件传递的内容。有几种方法可以做到这一点,例如将父组件中定义的回调函数作为可以进行此类更改的 prop 传递。但对于此示例,使用 state 可能更容易/更适用。

请记住,您希望更改组件的state以反映您想要查看的内容(您想要render的内容(。因此,假设您在组件的state中有一个名为 items 的数组。假设你是

class ListDemo extends React.component {
  constructor() {
    super()
    // initialize state
    this.state = {
      items: ['thing1', 'thing2', 'thing3']
    }
  }
  onClick(index) {
    // newItems is a new array with the element at the given index removed
    // this logic doesn't handle edge cases, but that's besides the point
    const newItems = [
      ...this.state.items.slice(0, index),
      ...this.state.items.slice(index + 1)
    ]
    // here we set this component's state's items to 
    // the new state with what we want removed.
    // it will then re-render the component to reflect the new state
    this.setState({
      items: newItems
    })
  }
  render() {
    return (
      <div>
        {
          // here we render buttons for each item in the component's state's items
          // we use `onClick` to make it so that clicking the button
          // will remove it from the list
          this.state.items.map((item, index) => {
            return (
              <button 
                onClick={() => this.onClick(index)}
                key={`${item}${index}`}
              >
                {item}
              </button>
            )
          })
        }
      </div>
    )
  }
}

让我们回顾一下此示例中发生的情况。首先,创建组件时,它的初始state设置一个包含 3 个元素的 items 数组。首次呈现时,它将为 items 数组中的每个元素创建一个按钮。请注意,呈现的内容完全由state决定。

每个按钮还有一个回调,单击时会调用该回调(由 onClick 设置(。此回调将从items数组中删除该特定元素,然后更新组件的state,以具有一个新的items数组,而不使用刚刚删除的元素。这反过来会导致重新呈现,该渲染使用新的items数组来显示按钮。这一次,我们通过单击它删除的按钮不再存在,因为它不再处于this.state.items中。

这是 react 的关键概念之一 - 组件是根据它们的propsstate渲染的,更改任何一个都会更新显示的内容。

至于为什么要使用箭头函数,那是因为它会自动将thisbindListDemo组件。同样,您可以使用类似 onClick={this.onClick.bind(this)} .这样做是必要的,因为单击按钮时this的值不能保证达到您的预期。阅读本文可能会使它更加清晰。