React js onClick can't pass value to method

后端 未结 30 1736
北荒
北荒 2020-11-22 07:05

I want to read the onClick event value properties. But when I click on it, I see something like this on the console:

SyntheticMouseEvent {dispatchConfig: Ob         


        
30条回答
  •  悲哀的现实
    2020-11-22 07:36

    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. 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(
              
                  {this.props.defaultColumns.map(function (column) {
                      return (
                          
                            {column}
                          
                      );
                  })}
                  {this.props.externalColumns.map(function (column) {
                      // Multi dimension array - 0 is column name
                      var externalColumnName = column[0];
                      return ( {externalColumnName}
                      );
                  })}
              );
          )
      }
    });
    
    // 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 (
          
        )        
      },
      _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. 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.

    Here's a CodePen demo showing this method in action.

提交回复
热议问题