React js onClick 无法将值传递给方法 [英] React js onClick can't pass value to method

查看:32
本文介绍了React js onClick 无法将值传递给方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取 onClick 事件值属性.但是当我点击它时,我在控制台上看到类似这样的内容:

I want to read the onClick event value properties. But when I click on it, I see something like this on the console:

SyntheticMouseEvent {dispatchConfig: Object, dispatchMarker: ".1.1.0.2.0.0:1", nativeEvent: MouseEvent, type: "click", target

我的代码运行正常.当我运行时,我可以看到 {column} 但无法在 onClick 事件中获取它.

My code is working correctly. When I run I can see {column} but can't get it in the onClick event.

我的代码:

var HeaderRows = React.createClass({
  handleSort:  function(value) {
    console.log(value);
  },
  render: function () {
    var that = this;
    return(
      <tr>
        {this.props.defaultColumns.map(function (column) {
          return (
            <th value={column} onClick={that.handleSort} >{column}</th>
          );
        })}
        {this.props.externalColumns.map(function (column) {
          // Multi dimension array - 0 is column name
          var externalColumnName = column[0];
          return ( <th>{externalColumnName}</th>);
        })}
      </tr>
    );
  }
});

如何将值传递给 React js 中的 onClick 事件?

How can I pass a value to the onClick event in React js?

推荐答案

Easy Way

使用箭头函数:

return (
  <th value={column} onClick={() => this.handleSort(column)}>{column}</th>
);

这将创建一个新函数,该函数使用正确的参数调用 handleSort.

This will create a new function that calls handleSort with the right params.

解压成一个子组件.在渲染调用中使用箭头函数的问题是它每次都会创建一个新函数,最终导致不必要的重新渲染.

Extract it into a sub-component. The problem with using an arrow function in the render call is it will create a new function every time, which ends up causing unneeded re-renders.

如果你创建一个子组件,你可以传递处理程序并使用 props 作为参数,然后只有当 props 改变时才会重新渲染(因为处理程序引用现在永远不会改变):

If you create a sub-component, you can pass handler and use props as the arguments, which will then re-render only when the props change (because the handler reference now never changes):

子组件

class TableHeader extends Component {
  handleClick = () => {
    this.props.onHeaderClick(this.props.value);
  }

  render() {
    return (
      <th onClick={this.handleClick}>
        {this.props.column}
      </th>
    );
  }
}

主要组件

{this.props.defaultColumns.map((column) => (
  <TableHeader
    value={column}
    onHeaderClick={this.handleSort}
  />
))}

<小时>

旧的简单方法 (ES5)

使用 .bind 传递你想要的参数,这样你就可以将函数与组件上下文绑定:

Use .bind to pass the parameter you want, this way you are binding the function with the Component context :

return (
  <th value={column} onClick={this.handleSort.bind(this, column)}>{column}</th>
);

这篇关于React js onClick 无法将值传递给方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆