简体   繁体   English

反应 onclick 将数组中的项目切换到前一个索引

[英]React onclick to switch the item in an array to previous index

I'm working on this React problem in which I need to shift the index in the array to previous index.我正在处理这个 React 问题,我需要将数组中的索引移动到上一个索引。 For example, I have the list = ["A", "B", "C"] mapped out into例如,我将list = ["A", "B", "C"]映射到

<ul>
<li>A</li>
<li>B</li>
<li>C</li>
</ul>

And if one person click on "B" in the list, it will be moved up like this如果一个人点击列表中的“B”,它会像这样向上移动

<ul>
<li>B</li>
<li>A</li>
<li>C</li>
</ul>

So here is my attempt that I couldn't get to work from Codepen :所以这是我无法从Codepen开始工作的尝试:

const List = (props) => {
  //   constructor(props) {
  //      super(props);
  //     this.state = {
  //       list: this.props.items
  //     }
  // }
  
  onItemClick = (e) => {
    // console.log("clickedthis", e);
    let currentArr = props.items;
    let current = e;
    let to;
    if(e === 0) {
      to = currentArr.length - 1;
    } else {
      to = e - 1;
    }
    console.log("to", to);
    console.log("array", currentArr);
    let from = currentArr.splice(current, 1)[0];
    // console.log("from", from);
    return props.items.splice(to, 0, from);
    
  }
  
  return  (
    <ul>
    {props.items.map((item, index) => {
      return (
        <li
          key={index} onClick={() => onItemClick(index)}>
          {item}
        </li>
      );
    })}
  </ul>
  )
  
}

document.body.innerHTML = "<div id='root'> </div>";
  
const rootElement = document.getElementById("root");
ReactDOM.render(<List items={["A", "B", "C"]} />, rootElement);

// let listItem = document.querySelectorAll("li")[1];
// if(listItem) {
//   listItem.click();
// }
setTimeout(() => console.log(document.getElementById("root").innerHTML));

I can't use constructor(props) in this code because it won't display the list.我不能在此代码中使用constructor(props) ,因为它不会显示列表。 I think it's called functional component which takes props as an argument and returns a react element.我认为它被称为功能组件,它将道具作为参数并返回一个反应元素。 So how do I get it to work to switch the array on click?那么如何让它在点击时切换阵列呢?

You need to use component's state to display the list because the React will rerender the component only on state change.您需要使用组件的 state 来显示列表,因为 React 将仅在 state 更改时重新呈现组件。

You are updating props.items directly and it will not rerender your component, also it's not a good idea to change the props value.您正在直接更新props.items并且它不会重新渲染您的组件,更改 props 值也不是一个好主意。

You can use below code:您可以使用以下代码:

const List = props => {
  const [items, setItems] = useState(props.items);

  const onItemClick = e => {
    const item = items[e];
    items.splice(e, 1);
    items.unshift(item);
    setItems([...items]);
  };

  return (
    <ul>
      {items.map((item, index) => {
        return (
          <li key={index} onClick={() => onItemClick(index)}>
            {item}
          </li>
        );
      })}
    </ul>
  );
};

Working Demo:工作演示:

https://codesandbox.io/s/gifted-dawn-gi0el https://codesandbox.io/s/gifted-dawn-gi0el

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

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