简体   繁体   English

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

[英]jquery vs react.js remove item from a list

 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>

I'm confused how stuff work here in react.js, I need presduo code how to passing work.我很困惑 react.js 中的东西是如何工作的,我需要 presduo 代码如何传递工作。 I was from jquery background, it's so straight forward, just get the right dom and do $(this).remove(), while in react I'm confused.我来自 jquery 背景,它是如此直接,只需获取正确的 dom 并执行 $(this).remove(),而在反应中我很困惑。

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

When you click what happened?当你点击发生了什么? arrow function for?箭头函数? and where does the remove come from?删除来自哪里?

React follows unidirectional data binding , which means, the data will flow in a single direction. React 遵循单向数据绑定,这意味着数据将沿单一方向流动。 So, the data is stored in a state .因此,数据存储在state Whenever the state changes the component will re-render .每当state改变时,组件将re-render A state can be changed at any point in time.可以在任何时间点更改状态。 But, mostly it will be changed on any action .但是,大多数情况下它会在任何action上发生变化。 In your case the action in onClick() .在您的情况下, onClick() This will call the function will the id of the element which triggered the onClick() .这将调用函数将触发onClick()的元素的id Now, in that function, you will iterate through the state , identify, remove and set the new state using setState() which will re-render the component with the new data.现在,在该函数中,您将使用setState()遍历state ,识别、删除和设置新状态,这将使用新数据重新渲染组件。 This render will not have the clicked element as it was removed from the state.此渲染将没有单击的元素,因为它已从状态中删除。

The remove() function is passed on to the child component from the parent component which can be accessed using props . remove()函数从可以使用props访问的父组件传递给子组件。 This will be a reference to the function declared in the parent component.这将是对父组件中声明的函数的引用。 During the click, using this reference, the function in the parent component will be called!在点击过程中,使用这个引用,会调用父组件中的函数!

In react, components are rendered based on their props and state .在 React 中,组件根据它们的propsstate进行渲染。 props are passed from the parent component, and a component may or may not have internal state . props从父组件传递,组件可能有也可能没有内部state

Using jQuery, you would try to remove it by removing the DOM node directly.使用 jQuery,您可以尝试通过直接删除 DOM 节点来删除它。 However, in react, interacting with the DOM directly is an anti-pattern.然而,在 React 中,直接与 DOM 交互是一种反模式。 Since the current state and props determines what is rendered, you want to change one of those that will cause a re-rendering and display something new.由于当前的stateprops决定了渲染的内容,因此您希望更改会导致重新渲染并显示新内容的那些。

In your case, it looks like you're trying to modify props directly.在您的情况下,您似乎正在尝试直接修改props props are read only and should not be modified. props是只读的,不应修改。 Since props are passed down from the parent component, you would have to change what's being passed down from the parent.因为props是从父组件传下来的,所以你必须改变从父组件传下来的东西。 There are a few ways you can do that, such as passing a callback function defined in the parent component as a prop that can make such a change.有几种方法可以做到这一点,例如将父组件中定义的回调函数作为可以进行此类更改的 prop 传递。 But for this example, it might be easier/more applicable to use state .但是对于这个例子,使用state可能更容易/更适用。

Remember, you want to change the component's state to reflect what you want to see (what you want to render ).请记住,您希望更改组件的state以反映您想要看到的内容(您想要render )。 So let's say you have an array called items in your component's state .因此,假设您在组件的state有一个名为items的数组。 And let's say you are让我们说你是

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>
    )
  }
}

Let's go over what is happening in this example.让我们回顾一下这个例子中发生的事情。 First, when the component is created, it's initial state is set with an items array that contains 3 elements.首先,当组件被创建时,它的初始state被设置为一个包含 3 个元素的items数组。 When it is first rendered, it will create a button for each element in the items array.当它第一次被渲染时,它会为items数组中的每个元素创建一个按钮。 Notice that what is rendered is purely determined by the state .请注意,呈现的内容完全由state决定。

Each button also has a callback that is called when it's clicked (set by onClick ).每个按钮还有一个回调,当它被点击时被调用(由onClick设置)。 This callback is what will remove that specific element from the items array and then update the component's state to have a new items array without the element that was just removed.此回调将从items数组中删除该特定元素,然后更新组件的state以拥有一个没有刚刚删除的元素的新items数组。 This in turn causes a re-rendering, which uses the new items array to display the buttons.这反过来会导致重新渲染,使用新的items数组来显示按钮。 This time around, the button we removed by click it is no longer there since it's no longer in this.state.items .这一次,我们通过单击它删除的按钮不再存在,因为它不再在this.state.items

That is one of the key concepts of react - components are rendered based on their props and state , and changing either will update what is displayed.这是 react 的关键概念之一——组件是根据它们的propsstate呈现的,改变任何一个都会更新显示的内容。

As for why to use an arrow function, it's because it will automatically bind the this value to the ListDemo component.至于为什么要使用箭头函数,是因为它会自动bind thisbindListDemo组件上。 Similarly, you can use something like onClick={this.onClick.bind(this)} .同样,您可以使用类似onClick={this.onClick.bind(this)} Doing this is necessary since the value of this when clicking the button isn't guaranteed to what you expect.这样做是必要的,因为单击按钮时this的值不能保证达到您的预期。 Reading this might make it more clear.阅读本文可能会更清楚。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM