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

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

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

我的代码:

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事件传递值?


当前回答

我想您必须将该方法绑定到React的类实例。使用构造函数绑定React中的所有方法更安全。在将参数传递给方法的情况下,第一个参数用于绑定方法的“this”上下文,因此无法访问方法内部的值。

其他回答

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

使用this.handleSort。js中没有关键字。谢谢兄弟。

onClick={this.handleSort}

如今,有了ES6,我觉得我们可以使用更新的答案。

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

基本上,(对于任何不知道的人)由于onClick期望传递给它一个函数,所以bind可以工作,因为它创建了一个函数的副本。相反,我们可以传递一个箭头函数表达式,它只调用我们想要的函数,并保留它。您应该永远不需要在React中绑定渲染方法,但如果由于某种原因,您在某个组件方法中丢失了这一点:

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

通过将count作为参数从主组件传递到子组件,实现显示对象的总计数,如下所述。

这里是MainComponent.js

import React, { Component } from "react";

import SubComp from "./subcomponent";

class App extends Component {

  getTotalCount = (count) => {
    this.setState({
      total: this.state.total + count
    })
  };

  state = {
    total: 0
  };

  render() {
    const someData = [
      { name: "one", count: 200 },
      { name: "two", count: 100 },
      { name: "three", count: 50 }
    ];
    return (
      <div className="App">
        {someData.map((nameAndCount, i) => {
          return (
            <SubComp
              getTotal={this.getTotalCount}
              name={nameAndCount.name}
              count={nameAndCount.count}
              key={i}
            />
          );
        })}
        <h1>Total Count: {this.state.total}</h1>
      </div>
    );
  }
}

export default App;

这里是SubComp.js

import React, { Component } from 'react';
export default class SubComp extends Component {

  calculateTotal = () =>{
    this.props.getTotal(this.props.count);
  }

  render() {
    return (
      <div>
        <p onClick={this.calculateTotal}> Name: {this.props.name} || Count: {this.props.count}</p>
      </div>
    )
  }
};

尝试实现上述内容,您将得到传递参数如何在任何DOM方法上的reactjs中工作的确切场景。

交替尝试回答OP的问题,包括e.preventDefault()调用:

渲染链接(ES6)

<a href="#link" onClick={(e) => this.handleSort(e, 'myParam')}>

组件功能

handleSort = (e, param) => {
  e.preventDefault();
  console.log('Sorting by: ' + param)
}