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


当前回答

下面是传递onClick事件值的示例。

我使用了es6语法。记住类内组件箭头函数不会自动绑定,所以在构造函数中显式绑定。

class HeaderRows extends React.Component {

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

    handleSort(value) {
        console.log(value);
    }

    render() {
        return(
            <tr>
                {this.props.defaultColumns.map( (column, index) =>
                    <th value={ column } 
                        key={ index } 
                        onClick={ () => this.handleSort(event.target.value) }>
                        { column }
                    </th>
                )}

                {this.props.externalColumns.map((column, index)  =>
                    <th value ={ column[0] }
                        key={ index }>
                        {column[0]}
                    </th>
                )}
            </tr>
         );
    }
}

其他回答

通过将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中工作的确切场景。

这里有很好的答案,我同意@Austin Greco(第二个选项,有单独的组件)还有一种我喜欢的方式,咖喱。您可以做的是创建一个接受一个参数(您的参数)的函数,并返回另一个接受另一个参数的函数(在本例中是单击事件)。那你就可以随心所欲了。

示例5:

handleChange(param) { // param is the argument you passed to the function
    return function (e) { // e is the event object that returned

    };
}

ES6:

handleChange = param => e => {
    // param is the argument you passed to the function
    // e is the event object that returned
};

您可以这样使用它:

<input 
    type="text" 
    onChange={this.handleChange(someParam)} 
/>

以下是此类用法的完整示例:

const someArr=[“A”,“B”,“C”,“D”];类应用程序扩展React.Component{状态={值A:“”,valueB:“一些初始值”,值C:“”,值D:“废话”};handleChange=param=>e=>{const nextValue=e.target.value;this.setState({[“value”+param]:nextValue});};render(){返回(<div>{someArr.map(obj=>{返回(<div><标签>{`输入${obj}`}</label><输入type=“文本”value={this.state[“value”+obj]}onChange={this.handleChange(obj)}/><br/><br/></div>);})}</div>);}}const rootElement=document.getElementById(“root”);ReactDOM.render(<App/>,rootElement);<script src=“https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js“></script><script src=“https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js“></script><div id=“root”></div>

请注意,这种方法不能解决每次渲染时创建新实例的问题。与其他内联处理程序相比,我更喜欢这种方法,因为在我看来,这种方法更简洁、可读。

编辑:如下面的注释所示,您可以缓存/记忆函数的结果。

这是一个简单的实现:

让备忘录={};const someArr=[“A”,“B”,“C”,“D”];类应用程序扩展React.Component{状态={值A:“”,valueB:“一些初始值”,值C:“”,值D:“废话”};handleChange=param=>{常量处理程序=e=>{const nextValue=e.target.value;this.setState({[“value”+param]:nextValue});}if(!memo[param]){备忘录[param]=e=>处理程序(e)}返回备忘录[param]};render(){返回(<div>{someArr.map(obj=>{返回(<div key={obj}><标签>{`输入${obj}`}</label><输入type=“文本”value={this.state[“value”+obj]}onChange={this.handleChange(obj)}/><br/><br/></div>);})}</div>);}}const rootElement=document.getElementById(“root”);ReactDOM.render(<App/>,rootElement);<script src=“https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js“></script><script src=“https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js“></script><div id=“root”/>

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

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

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

这是我的方法,不知道有多糟糕,请评论

在可单击元素中

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

然后

handleSort(e){
    this.sortOn(e.currentTarget.getAttribute('data-column'));
}