将处理程序从 class 传递到循环中的组件

Pass a handler from class to component in loop

我想将点击句柄 (handleDeleteUser) 传递给其他组件,实际上是从 user.js 到 DropDownUserTool.js:

User.js

handleDeleteUser = (id) => {
  alert(id);
};
...
// in render
User.data.map(function (User, i) {
  return (
    <DropDownUserTool
      id={User.id}
      click={(e) => {
        this.handleDeleteUser(e);
      }}
    />
  );
});

DropDownUserTool.js

const DropDownUserTool = (props) => {
  return (
    <ButtonDropdown isOpen={dropdownOpen} toggle={toggle}>
      <DropdownToggle color="secondary" caret>
        tools
      </DropdownToggle>
      <DropdownMenu>
        <DropdownItem>
          <Link to={"/User/Edit/" + props.id}>Edit</Link>
        </DropdownItem>
        <DropdownItem onClick={() => props.click(props.id)}>
          Delete
        </DropdownItem>
      </DropdownMenu>
    </ButtonDropdown>
  );
};

但是点击后return报错:

TypeError: Cannot read properties of undefined (reading 'handleDeleteUser')

这一行:

{this.handleDeleteUser(e)}}/>

当您制作地图时,您使用的是标准函数调用并丢失了上下文。请改用箭头函数。

class User extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [{ id: 1 }, { id: 2 }, { id: 3 }]
    };
  }

  handleDeleteUser = (id) => alert(id);

  render() {
    return (
      <div>
        // this needs to be an arrow function
        // that way you won't change the context of `this`
        {this.state.data.map((item, i) => {
          return (
            <DropDownUserTool
              id={item.id}
              key={item.id}
              handleDelete={this.handleDeleteUser }
            />
          );
        })}
      </div>
    );
  }
}

const DropDownUserTool = ({ handleDelete, id }) => (
  <button onClick={() => handleDelete(id)}>Delete</button>
);

您正试图在 map 内达到 this,只需定义 this!在 render 循环之前:

let realthis = this;

然后像这样调用你的处理程序:

<DropDownUserTool id={User.id} click={(e) => {realthis.handleDeleteUser(e)}}/>