我想读取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事件传递值?


当前回答

您只需要使用Arrow函数来传递值。

<buttonClick={()=>this.props.onClickHandle(“StackOverFlow”)}>

确保使用()=>,否则将在没有单击事件的情况下调用单击方法。

注意:崩溃检查默认方法

请在下面的codesandbox中找到相同的运行代码。

用方法反应传递值

其他回答

使用封口,可获得干净的解决方案:

<th on单击={this.handleSort(column)}>{column}</th>

handleSort函数将返回已设置值列的函数。

handleSort: function(value) { 
    return () => {
        console.log(value);
    }
}

当用户单击th时,将使用正确的值调用匿名函数。

例子:https://stackblitz.com/edit/react-pass-parameters-example

有三种方法可以处理此问题:-

将构造函数中的方法绑定为:-导出类HeaderRows扩展组件{构造器(){super();this.handleSort=this.handleSort.bind(this);}}将箭头函数创建为:-手柄端口=()=>{//这里有些文字}第三种方式是:-<th value={column}onClick={()=>that.handleSort}>{column}</th>

使用箭头功能:

您必须安装阶段2:

npm安装babel-preset-stage-2:

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            value=0
        }
    }

    changeValue = (data) => (e) => {
        alert(data);  //10
        this.setState({ [value]: data })
    }

    render() {
        const data = 10;
        return (
            <div>
                <input type="button" onClick={this.changeValue(data)} />
            </div>
        );
    }
}
export default App; 
1. You just have to use an arrow function in the Onclick event like this: 

<th value={column} onClick={() => that.handleSort(theValue)} >{column}</th>

2.Then bind this in the constructor method:
    this.handleSort = this.handleSort.bind(this);

3.And finally get the value in the function:
  handleSort(theValue){
     console.log(theValue);
}

这是一个非常简单的方法。

 onClick={this.toggleStart('xyz')} . 
  toggleStart= (data) => (e) =>{
     console.log('value is'+data);  
 }