React js onClick无法将值传递给方法

本文翻译自:React js onClick can't pass value to method

I want to read the onClick event value properties. 我想阅读onClick事件值属性。 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

My code is working correctly. 我的代码正常工作。 When I run I can see {column} but can't get it in the onClick event. 当我运行时,我可以看到{column}但是在onClick事件中无法获取它。

My Code: 我的代码:

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>
    );
  }
});

How can I pass a value to the onClick event in React js? 如何在React js中将值传递给onClick事件?


#1楼

参考:https://stackoom.com/question/215BC/React-js-onClick无法将值传递给方法


#2楼

Easy Way 简单的方法

Use an arrow function: 使用箭头功能:

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

This will create a new function that calls handleSort with the right params. 这将创建一个新函数,该函数使用正确的参数调用handleSort

Better Way 更好的方法

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. 在render调用中使用箭头函数的问题是,每次都会创建一个新函数,最终导致不必要的重新渲染。

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): 如果创建子组件,则可以传递处理程序并将props用作参数,然后仅当props更改时才重新渲染(因为现在处理程序引用不再更改):

Sub-component 子组件

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

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

Main component 主要成分

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

Old Easy Way (ES5) 旧的简便方法(ES5)

Use .bind to pass the parameter you want: 使用.bind传递所需的参数:

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

#3楼

I would recommend curry over bind in this case. 在这种情况下,我会建议curry over bind。 Like, 喜欢,

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

#4楼

Nowadays, with ES6, I feel we could use an updated answer. 如今,有了ES6,我觉得我们可以使用更新的答案。

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

Basically, (for any that don't know) since onClick is expecting a function passed to it, bind works because it creates a copy of a function. 基本上,(对于任何不知道的人)由于onClick期望将函数传递给它,因此bind可以工作,因为它创建了函数的副本。 Instead we can pass an arrow function expression that simply invokes the function we want, and preserves this . 相反,我们可以传递一个箭头函数表达式,该表达式仅调用所需的函数并保留this You should never need to bind the render method in React, but if for some reason you're losing this in one of your component methods: 您永远不需要在React中绑定render方法,但是如果由于某种原因而在一个组件方法中丢失了this

constructor(props) {
  super(props);
  this.myMethod = this.myMethod.bind(this);
}

#5楼

class extends React.Component {
    onClickDiv = (column) => {
        // do stuff
    }
    render() {
        return <div onClick={() => this.onClickDiv('123')} />
    }
}

#6楼

One more option not involving .bind or ES6 is to use a child component with a handler to call the parent handler with the necessary props. 不涉及.bind或ES6的另一种选择是使用带有处理程序的子组件,以使用必要的道具来调用父处理程序。 Here's an example (and a link to working example is below): 这是一个示例(下面是工作示例的链接):

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

// A child component to pass the props back to the parent handler
var TableHeader = React.createClass({
  propTypes: {
    value: React.PropTypes.string,
    onClick: React.PropTypes.func
  },
  render: function () {
    return (
      <th value={this.props.value} onClick={this._handleClick}
        {this.props.children}
      </th>
    )        
  },
  _handleClick: function () {
    if (this.props.onClick) {
      this.props.onClick(this.props.value);
    }
  }
});

The basic idea is for the parent component to pass the onClick function to a child component. 基本思想是父组件将onClick函数传递给子组件。 The child component calls the onClick function and can access any props passed to it (and the event ), allowing you to use any event value or other props within the parent's onClick function. 子组件调用onClick函数,并且可以访问传递给它的任何props (和event ),从而允许您在父项的onClick函数中使用任何event值或其他道具。

Here's a CodePen demo showing this method in action. 这是一个CodePen演示,展示了此方法的实际作用。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值