React sortable hoc-onClick如何更改状态

时间:2019-05-17 03:41:26

标签: reactjs react-sortable-hoc

使用react sortable hoc网格示例,我想添加一个按钮,当我单击它时,它将更改状态。这是代码:https://codesandbox.io/s/pedantic-grass-5zv2k

当我点击“更多详细信息”按钮时,我想将this.state.test状态更改为true

1 个答案:

答案 0 :(得分:0)

这应该可以完成

import React, { Component } from "react";
import { render } from "react-dom";
import {
  arrayMove,
  SortableElement,
  SortableContainer
} from "react-sortable-hoc";

const gridStyles = {
  display: "grid",
  gridTemplateColumns: "repeat(4, 1fr)",
  gridGap: "16px"
};

const gridItemStyles = {
  height: "100px",
  backgroundColor: "#e5e5e5"
};

const GridItem = SortableElement(({ value,handleItemClick }) => (
  <div style={gridItemStyles}>
    {value}
    <button onClick={handleItemClick}>more details</button>
  </div>
));

const Grid = SortableContainer(({ items,handleClick }) => (
  <div style={gridStyles}>
    {items.map((value, index) => (
      <GridItem 
      handleItemClick={handleClick}
      key={`item-${index}`} 
      index={index} 
      value={value} />
    ))}
  </div>
));

class App extends Component {
  state = {
    items: Array.apply(null, Array(100)).map((val, index) => `Item ${index}`),
    test: false
  };

  onSortEnd = ({ oldIndex, newIndex }) => {
    this.setState({
      items: arrayMove(this.state.items, oldIndex, newIndex)
    });
  };

  moreDetialsButton = () => {
    console.log("ss");

    this.setState({
      test: true
    });
  };



  render() {
    return (
      <div>
        {this.state.test ? "yes" : "no"}
        <Grid handleClick={this.moreDetialsButton} items={this.state.items} onSortEnd={this.onSortEnd} axis="xy" />
      </div>
    );
  }


}

render(<App />, document.getElementById("root"));

相关问题