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


当前回答

这个例子可能和你的有点不同。但我可以向你保证,这是解决这个问题的最佳方案。我已经找了好几天没有性能问题的解决方案。终于想出了这个。

class HtmlComponent extends React.Component {
  constructor() {
    super();
    this.state={
       name:'MrRehman',
    };
    this.handleClick= this.handleClick.bind(this);
  }

  handleClick(event) {
    const { param } = e.target.dataset;
    console.log(param);
    //do what you want to do with the parameter
  }

  render() {
    return (
      <div>
        <h3 data-param="value what you wanted to pass" onClick={this.handleClick}>
          {this.state.name}
        </h3>
      </div>
    );
  }
}

更新

如果您想处理应该作为参数的对象。您可以使用JSON.stringify(对象)将其转换为字符串并添加到数据集。

return (
   <div>
     <h3 data-param={JSON.stringify({name:'me'})} onClick={this.handleClick}>
        {this.state.name}
     </h3>
   </div>
);

其他回答

这里有很好的答案,我同意@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”/>

我意识到这已经很晚了,但我认为一个更简单的解决方案可以满足许多用例:

    handleEdit(event) {
        let value = event.target.value;
    }

    ...

    <button
        value={post.id}
        onClick={this.handleEdit} >Edit</button>

我想你也可以使用数据属性。

简单、语义。

不知从何而来回答这个问题,但我认为,bind会奏效。找到下面的示例代码。

const handleClick = (data) => {
    console.log(data)
}

<button onClick={handleClick.bind(null, { title: 'mytitle', id: '12345' })}>Login</button>

这个例子可能和你的有点不同。但我可以向你保证,这是解决这个问题的最佳方案。我已经找了好几天没有性能问题的解决方案。终于想出了这个。

class HtmlComponent extends React.Component {
  constructor() {
    super();
    this.state={
       name:'MrRehman',
    };
    this.handleClick= this.handleClick.bind(this);
  }

  handleClick(event) {
    const { param } = e.target.dataset;
    console.log(param);
    //do what you want to do with the parameter
  }

  render() {
    return (
      <div>
        <h3 data-param="value what you wanted to pass" onClick={this.handleClick}>
          {this.state.name}
        </h3>
      </div>
    );
  }
}

更新

如果您想处理应该作为参数的对象。您可以使用JSON.stringify(对象)将其转换为字符串并添加到数据集。

return (
   <div>
     <h3 data-param={JSON.stringify({name:'me'})} onClick={this.handleClick}>
        {this.state.name}
     </h3>
   </div>
);

我编写了一个包装器组件,可用于此目的,该组件基于此处接受的答案。如果你只需要传递一个字符串,那么只需添加一个数据属性并从e.target.dataset中读取它(就像其他人建议的那样)。默认情况下,我的包装器将绑定到任何以“on”开头的属性,并在所有其他事件参数之后自动将数据属性传递回调用者。虽然我还没有测试过它的性能,但它会让您有机会避免自己创建类,并且可以这样使用:

const DataButton=带数据(“按钮”)

const DataInput=with Data('input');

或组件和功能

const DataInput=with Data(SomeComponent);

或者如果你愿意

const DataButton=with Data(<button/>)

声明在你的集装箱外(靠近你的进口)

以下是容器中的用法:

import withData from './withData';
const DataInput = withData('input');

export default class Container extends Component {
    state = {
         data: [
             // ...
         ]
    }

    handleItemChange = (e, data) => {
        // here the data is available 
        // ....
    }

    render () {
        return (
            <div>
                {
                    this.state.data.map((item, index) => (
                        <div key={index}>
                            <DataInput data={item} onChange={this.handleItemChange} value={item.value}/>
                        </div>
                    ))
                }
            </div>
        );
    }
}

下面是包装器代码'withData.js:

import React, { Component } from 'react';

const defaultOptions = {
    events: undefined,
}

export default (Target, options) => {
    Target = React.isValidElement(Target) ? Target.type : Target;
    options = { ...defaultOptions, ...options }

    class WithData extends Component {
        constructor(props, context){
            super(props, context);
            this.handlers = getHandlers(options.events, this);        
        }

        render() {
            const { data, children, ...props } = this.props;
            return <Target {...props} {...this.handlers} >{children}</Target>;
        }

        static displayName = `withData(${Target.displayName || Target.name || 'Component'})`
    }

    return WithData;
}

function getHandlers(events, thisContext) {
    if(!events)
        events = Object.keys(thisContext.props).filter(prop => prop.startsWith('on') && typeof thisContext.props[prop] === 'function')
    else if (typeof events === 'string')
        events = [events];

    return events.reduce((result, eventType) => {
        result[eventType] = (...args) => thisContext.props[eventType](...args, thisContext.props.data);
        return result;
    }, {});
}