首页 > 解决方案 > 仅在单击时使用参数调用函数的正确方法是什么?

问题描述

我试图通过传递来调用点击函数params,但没有发生。页面加载后,我的所有函数都会被调用。

处理参数的正确方法是什么onClick

这是我的代码:

import React, { Component } from "react";
import { inject, observer } from "mobx-react";

@inject("store")
@observer
class ToDoList extends Component {
  constructor(props) {
    super(props);
    this.store = props.store;
    this.todoName = React.createRef();
  }

  formHandler = e => {
    e.preventDefault();
    this.store.listUpdater(this.todoName.current.value);
    e.target.reset();
  };

  showItem = item => {
    console.log(item);
  };
  render() {
    return (
      <div>
        <ul>
          {this.store.Store.todo.map(item => (
            <li onClick={this.showItem(item)}>{item}</li> 
            //calls on page loads.. looking to call only on click!!
          ))}
        </ul>
        <form onSubmit={this.formHandler}>
          <div className="form-group">
            <input type="text" ref={this.todoName} />
          </div>
        </form>
      </div>
    );
  }
}

export default ToDoList;

标签: reactjs

解决方案


有几种方法,真的。

快速简单,但不太推荐:

就编程而言,此解决方案是最快的,因为它们都是单行的。它们的缺点是,每当您的组件重新渲染时,您都会生成一个新函数(就是这样() => ...做的)。这通常不是什么大问题,但它可能会在较大的集合中为您的渲染引入一些额外的延迟。不过,通常这可以忽略不计。

<li onClick={() => this.showItem(item)}>{item}</li>

或者

<li onClick={this.showItem.bind(this, item)}>{item}</li>

更详细,但推荐:

推荐的方法是只定义一次函数及其参数。在这里,我们onClick不会在每次重新渲染时获得一个新函数。相反,它有一个静态引用,this.click它调用我们作为 prop 从父级传递的回调以及参数。

<MyListItem onClick={this.showItem} item={item} />

您将在哪里MyListItem编写自定义组件。就像是:

class MyListItem extends React.Component {
  constructor() {
    super();
    this.click = this.click.bind(this);
  }

  click() {
    this.props.onClick(this.props.item);
  }

  render() {
    return (
      <li onClick={this.click}>{this.props.item}</li>
    );
  }
}

推荐阅读