React JS onClick nie może przekazać wartości do metody

Chcę odczytać właściwości wartości zdarzenia onClick. Ale jak na niego klikam to widzę coś takiego na konsoli:

SyntheticMouseEvent {dispatchConfig: Object, dispatchMarker: ".1.1.0.2.0.0:1", nativeEvent: MouseEvent, type: "click", target
Mój kod działa poprawnie. Po uruchomieniu widzę {column}, ale nie mogę go uzyskać w zdarzeniu onClick.

Mój Kod:

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>
    );
  }
});

Jak mogę przekazać wartość do zdarzenia onClick w Reaccie js?

Author: JGallardo, 2015-04-22

30 answers

Easy Way

Użyj funkcji strzałki:

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

Spowoduje to utworzenie nowej funkcji, która wywoła handleSort z odpowiednimi parametrami.

Better Way

Wyodrębnij go do podskładnika. Problem z użyciem funkcji strzałki w wywołaniu renderowania polega na tym, że za każdym razem tworzy ona nową funkcję, co powoduje niepotrzebne ponowne renderowanie.

Jeśli utworzysz pod-komponent, możesz przekazać obsługę i użyć właściwości jako argumentów, które będą ponownie renderowane tylko wtedy, gdy Właściwości się zmieniają (ponieważ Referencja obsługi nigdy się nie zmienia):

Podskładnik

class TableHeader extends Component {
  handleClick = () => {
    this.props.onHeaderClick(this.props.value);
  }

  render() {
    return (
      <th onClick={this.handleClick}>
        {this.props.column}
      </th>
    );
  }
}

główny składnik

{this.props.defaultColumns.map((column) => (
  <TableHeader
    value={column}
    onHeaderClick={this.handleSort}
  />
))}

Old Easy Way (ES5)

Użycie .bind aby przekazać żądany parametr, w ten sposób powiązujesz funkcję z kontekstem komponentu:

return (
  <th value={column} onClick={this.handleSort.bind(this, column)}>{column}</th>
);
 1392
Author: Austin Greco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-06-18 21:54:39

Są tu ładne odpowiedzi i zgadzam się z @ Austin Greco (druga opcja z oddzielnymi komponentami)
Jest inny sposób, który lubię, currying .
Możesz utworzyć funkcję, która akceptuje parametr (Twój parametr) i zwróci inną funkcję, która akceptuje inny parametr(w tym przypadku Zdarzenie click). wtedy możesz z nim robić, co tylko chcesz.

ES5:

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
};

I użyjesz to tak:

<input 
    type="text" 
    onChange={this.handleChange(someParam)} 
/>
Oto pełny przykład takiego użycia:

const someArr = ["A", "B", "C", "D"];

class App extends React.Component {
  state = {
    valueA: "",
    valueB: "some initial value",
    valueC: "",
    valueD: "blah blah"
  };

  handleChange = param => e => {
    const nextValue = e.target.value;
    this.setState({ ["value" + param]: nextValue });
  };

  render() {
    return (
      <div>
        {someArr.map(obj => {
          return (
            <div>
              <label>
                {`input ${obj}   `}
              </label>
              <input
                type="text"
                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>

Zauważ, że takie podejście nie rozwiązuje problemu tworzenia nowej instancji przy każdym renderowaniu.
Podoba mi się to podejście w stosunku do innych inline handlerów, ponieważ ten jest bardziej zwięzły i czytelny moim zdaniem.

Edit:
Jak sugerowano w komentarzach poniżej, możesz buforować / zapisywać wynik funkcji.

Oto naiwna implementacja:

let memo = {};

const someArr = ["A", "B", "C", "D"];

class App extends React.Component {
  state = {
    valueA: "",
    valueB: "some initial value",
    valueC: "",
    valueD: "blah blah"
  };

  handleChange = param => {
    const handler = e => {
      const nextValue = e.target.value;
      this.setState({ ["value" + param]: nextValue });
    }
    if (!memo[param]) {
      memo[param] = e => handler(e)
    }
    return memo[param]
  };

  render() {
    return (
      <div>
        {someArr.map(obj => {
          return (
            <div key={obj}>
              <label>
                {`input ${obj}   `}
              </label>
              <input
                type="text"
                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" />
 156
Author: Sagiv b.g,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-02-06 21:08:12

W dzisiejszych czasach, z ES6, myślę, że przydałaby się zaktualizowana odpowiedź.

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

Zasadniczo (dla każdego, kto nie wie) ponieważ onClick oczekuje przekazanej funkcji, bind działa, ponieważ tworzy kopię funkcji. Zamiast tego możemy przekazać wyrażenie funkcji strzałki, które po prostu wywołuje żądaną funkcję i zachowuje this. Nigdy nie powinieneś wiązać metody render W Reaccie, ale jeśli z jakiegoś powodu tracisz this w jednej ze swoich metod komponentowych:

constructor(props) {
  super(props);
  this.myMethod = this.myMethod.bind(this);
}
 123
Author: aikeru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-02 13:56:45

[[h / t do @E. Sundin za linkowanie tego w komentarzu]

Górna odpowiedź (funkcje anonimowe lub wiązanie) będzie działać, ale nie jest najbardziej wydajna, ponieważ tworzy kopię obsługi zdarzenia dla każdej instancji wygenerowanej przez funkcję map().

To jest wyjaśnienie optymalnego sposobu, aby to zrobić z ESLint-plugin-react :

Listy Pozycji

Powszechnym przypadkiem użycia bind w renderowaniu jest renderowanie listy, aby mieć a osobne wywołanie zwrotne dla pozycji listy:

const List = props => (
      <ul>
        {props.items.map(item =>
          <li key={item.id} onClick={() => console.log(item.id)}>
            ...
          </li>
        )}
      </ul>
    );

Zamiast robić to w ten sposób, przeciągnij powtarzaną sekcję do własnej "komponent": {]}

const List = props => (
      <ul>
        {props.items.map(item =>
          <ListItem 
            key={item.id} 
            item={item} 
            onItemClick={props.onItemClick} // assume this is passed down to List
           />
        )}
      </ul>
    );


const ListItem = props => {
  const _onClick = () => {
    console.log(props.item.id);
  }
    return (
      <li onClick={_onClick}>
        ...
      </li>
    );

});

Przyspieszy to renderowanie, ponieważ pozwala uniknąć konieczności tworzenia nowych funkcje (poprzez wywołania bind) przy każdym renderowaniu.

 74
Author: Brandon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-09 14:45:19

To jest moje podejście, Nie wiem jak źle jest, proszę skomentować

W elemencie klikalnym

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

A następnie

handleSort(e){
    this.sortOn(e.currentTarget.getAttribute('data-column'));
}
 26
Author: Santiago Ramirez,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-24 20:46:13

Ten przykład może się nieco różnić od Twojego. ale zapewniam cię, że jest to najlepsze rozwiązanie, jakie możesz mieć na ten problem. szukałem od kilku dni rozwiązania, które nie ma problemu z wydajnością. i w końcu wymyśliłem to.

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>
    );
  }
}

UPDATE

Okaz, że chcesz zajmować się obiektami, które mają być parametrami. możesz użyć JSON.stringify(object), Aby przekonwertować go na ciąg znaków i dodać do zestawu danych.

return (
   <div>
     <h3 data-param={JSON.stringify({name:'me'})} onClick={this.handleClick}>
        {this.state.name}
     </h3>
   </div>
);
 19
Author: hannad rehman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-09-15 09:58:14
class extends React.Component {
    onClickDiv = (column) => {
        // do stuff
    }
    render() {
        return <div onClick={() => this.onClickDiv('123')} />
    }
}
 7
Author: Vladimirs Matusevics,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-29 10:58:03

Po prostu utwórz taką funkcję

  function methodName(params) {
    //the thing  you wanna do
  }

I zadzwoń do niego w miejscu, którego potrzebujesz

 <Icon onClick = {() => { methodName(theParamsYouwantToPass);} }/>
 7
Author: Charith Jayasanka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-20 08:21:31

Zdaję sobie sprawę, że to dość późno na imprezę, ale myślę, że znacznie prostsze rozwiązanie może zaspokoić wiele przypadków użycia: {]}

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

    ...

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

Zakładam, że możesz również użyć atrybutu data-.

Proste, semantyczne.
 5
Author: jhchnc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-04-05 17:41:25

Jeszcze jedną opcją nie obejmującą .bind lub ES6 jest użycie komponentu potomnego z obsługą do wywołania obsługi rodzicielskiej z niezbędnymi właściwościami. Oto przykład (a link do przykładu roboczego znajduje się poniżej):

var HeaderRows = React.createClass({
  handleSort:  function(value) {
     console.log(value);
  },
  render: function () {
      var that = this;
      return(
          <tr>
              {this.props.defaultColumns.map(function (column) {
                  return (
                      <TableHeader value={column} onClick={that.handleSort} >
                        {column}
                      </TableHeader>
                  );
              })}
              {this.props.externalColumns.map(function (column) {
                  // Multi dimension array - 0 is column name
                  var externalColumnName = column[0];
                  return ( <th>{externalColumnName}</th>
                  );
              })}
          </tr>);
      )
  }
});

// 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 (
      <th value={this.props.value} onClick={this._handleClick}
        {this.props.children}
      </th>
    )        
  },
  _handleClick: function () {
    if (this.props.onClick) {
      this.props.onClick(this.props.value);
    }
  }
});

Podstawową ideą jest przekazanie przez komponent macierzysty funkcji onClick komponentowi potomnemu. Komponent potomny wywołuje funkcję onClick i może uzyskać dostęp do dowolnej props przekazanej do niej (oraz event), pozwalając na użycie dowolnej wartości event lub innych właściwości w obrębie onClick funkcja.

Oto demo CodePen pokazujące tę metodę w akcji.

 4
Author: Brett DeWoody,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-20 05:36:24

Dokonywanie alternatywnej próby odpowiedzi na pytanie OP, w tym wywołania e. preventDefault ():

Rendered link ( ES6 )

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

Funkcja Składowa

handleSort = (e, param) => {
  e.preventDefault();
  console.log('Sorting by: ' + param)
}
 4
Author: Po Rith,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-06 16:48:58

Możesz to po prostu zrobić, jeśli używasz ES6.

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}>
                  <Input onChange={(event) => this.handItemChange(event, 
                         item)} value={item.value}/>
              </div>
           ))
        }
        </div>
     );
   }
 }
 3
Author: Louis Alonzo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-21 11:49:02

Implementacja wyświetla całkowitą liczbę z obiektu, przekazując liczbę jako parametr z głównego do podrzędnych komponentów, jak opisano poniżej.

Oto 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;

A oto 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>
    )
  }
};

Spróbuj zaimplementować powyżej, a otrzymasz dokładny scenariusz działania parametrów pass w ReactJS na dowolnej metodzie DOM.

 3
Author: nandu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-24 18:29:27

Napisałem komponent wrapper, który można ponownie wykorzystać do tego celu, który opiera się na zaakceptowanych odpowiedziach tutaj. Jeśli wszystko, co musisz zrobić, to przekazać ciąg znaków, po prostu Dodaj atrybut data-i odczytaj go z e. target.zestaw danych (jak niektórzy inni sugerowali). Domyślnie mój wrapper będzie wiązał się z dowolnym propem, który jest funkcją i zaczyna się od " on " i automatycznie przekazuje propa danych z powrotem do wywołującego po wszystkich innych argumentach zdarzenia. Chociaż nie testowałem go pod kątem wydajności, da masz możliwość unikania tworzenia klasy samodzielnie, a można jej użyć w ten sposób:

const DataButton = withData('button')
const DataInput = withData('input');

Lub dla elementów i Funkcji

const DataInput = withData(SomeComponent);

Lub jeśli wolisz

const DataButton = withData(<button/>)

Zadeklaruj, że poza twoim kontenerem (w pobliżu Twojego importu)

Oto użycie w kontenerze:

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>
        );
    }
}

Oto kod wrappera ' 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;
    }, {});
}
 3
Author: SlimSim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-27 08:44:58

Mam poniżej 3 sugestie do tego na JSX onclick Events -

  1. Właściwie, nie musimy używać .funkcja bind() lub Strzałka w naszym kodzie. Możesz w prosty sposób użyć kodu.

  2. Można również przenieść Zdarzenie onClick z th(lub ul) do TR(lub li), aby poprawić wydajność. Zasadniczo będziesz miał n liczbę "słuchaczy zdarzeń" dla Twojego elementu n li.

    So finally code will look like this:
    <ul onClick={this.onItemClick}>
        {this.props.items.map(item =>
               <li key={item.id} data-itemid={item.id}>
                   ...
               </li>
          )}
    </ul>
    

    / / i możesz uzyskać dostęp do item.id w metodzie onItemClick, Jak pokazano poniżej:

    onItemClick = (event) => {
       console.log(e.target.getAttribute("item.id"));
    }
    
  3. Zgadzam się z powyższym podejściem do tworzenia osobnego komponentu Reactowego dla ListItem i List. Ten kod sprawia, że wygląda dobrze, jednak jeśli masz 1000 li, to zostanie utworzonych 1000 słuchaczy zdarzeń. Upewnij się, że nie powinieneś mieć dużo słuchacza zdarzeń.

    import React from "react";
    import ListItem from "./ListItem";
    export default class List extends React.Component {
    
        /**
        * This List react component is generic component which take props as list of items and also provide onlick
        * callback name handleItemClick
        * @param {String} item - item object passed to caller
        */
        handleItemClick = (item) => {
            if (this.props.onItemClick) {
                this.props.onItemClick(item);
            }
        }
    
        /**
        * render method will take list of items as a props and include ListItem component
        * @returns {string} - return the list of items
        */
        render() {
            return (
                <div>
                  {this.props.items.map(item =>
                      <ListItem key={item.id} item={item} onItemClick={this.handleItemClick}/>
                  )}
                </div>
            );
        }
    
    }
    
    
    import React from "react";
    
    export default class ListItem extends React.Component {
        /**
        * This List react component is generic component which take props as item and also provide onlick
        * callback name handleItemClick
        * @param {String} item - item object passed to caller
        */
        handleItemClick = () => {
            if (this.props.item && this.props.onItemClick) {
                this.props.onItemClick(this.props.item);
            }
        }
        /**
        * render method will take item as a props and print in li
        * @returns {string} - return the list of items
        */
        render() {
            return (
                <li key={this.props.item.id} onClick={this.handleItemClick}>{this.props.item.text}</li>
            );
        }
    }
    
 2
Author: Reetesh Agrawal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-09 21:31:54

Dodałem kod dla onclick event value pass DO METODY na dwa sposoby . 1 . używając metody bind 2. używając metody arrow (=>). zobacz metody handlesort1 i handlesort

var HeaderRows  = React.createClass({
    getInitialState : function() {
      return ({
        defaultColumns : ["col1","col2","col2","col3","col4","col5" ],
        externalColumns : ["ecol1","ecol2","ecol2","ecol3","ecol4","ecol5" ],

      })
    },
    handleSort:  function(column,that) {
       console.log(column);
       alert(""+JSON.stringify(column));
    },
    handleSort1:  function(column) {
       console.log(column);
       alert(""+JSON.stringify(column));
    },
    render: function () {
        var that = this;
        return(
        <div>
            <div>Using bind method</div>
            {this.state.defaultColumns.map(function (column) {
                return (
                    <div value={column} style={{height : '40' }}onClick={that.handleSort.bind(that,column)} >{column}</div>
                );
            })}
            <div>Using Arrow method</div>

            {this.state.defaultColumns.map(function (column) {
                return (
                    <div value={column} style={{height : 40}} onClick={() => that.handleSort1(column)} >{column}</div>

                );
            })}
            {this.state.externalColumns.map(function (column) {
                // Multi dimension array - 0 is column name
                var externalColumnName = column;
                return (<div><span>{externalColumnName}</span></div>
                );
            })}

        </div>);
    }
});
 2
Author: Merugu Prashanth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-12 09:19:02

Poniżej znajduje się przykład, który przekazuje wartość w zdarzeniu onClick.

Użyłem składni es6. pamiętaj w komponencie klasy funkcja strzałki nie wiąże się automatycznie, więc jawnie wiąże w konstruktorze.

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>
         );
    }
}
 2
Author: Karan Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-09 10:12:26

Domyślam się, że będziesz musiał powiązać metodę z instancją klasy Reacta. Bezpieczniej jest użyć konstruktora, aby powiązać wszystkie metody w Reaccie. W Twoim przypadku, gdy przekazujesz parametr do metody, pierwszy parametr jest używany do powiązania kontekstu 'this' metody, więc nie możesz uzyskać dostępu do wartości wewnątrz metody.

 2
Author: Andysenclave,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-10 04:06:44
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);
}
 2
Author: Juan David Arce,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-10 20:57:20

To bardzo prosty sposób.

 onClick={this.toggleStart('xyz')} . 
  toggleStart= (data) => (e) =>{
     console.log('value is'+data);  
 }
 2
Author: Romia Mukherjee,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-27 18:49:00
class TableHeader extends Component {
  handleClick = (parameter,event) => {
console.log(parameter)
console.log(event)

  }

  render() {
    return (
      <button type="button" 
onClick={this.handleClick.bind(this,"dataOne")}>Send</button>
    );
  }
}
 2
Author: Anik Mazumder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-03-10 06:53:41

Pojawiając się znikąd na to pytanie, ale myślę, że wystarczy. Poniżej znajdziesz przykładowy kod.

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

<button onClick={handleClick.bind(null, { title: 'mytitle', id: '12345' })}>Login</button>
 2
Author: Charitha Goonewardena,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-11-01 12:28:18

Istnieje kilka sposobów przekazywania parametrów w procedurach obsługi zdarzeń, niektóre z nich są następujące.

Możesz użyć funkcji strzałki do owinięcia wokół obsługi zdarzenia i przekazania parametrów:

<button onClick={() => this.handleClick(id)} />

Powyższy przykład jest równoznaczny z wywołaniem .bind lub można jawnie wywołać bind.

<button onClick={this.handleClick.bind(this, id)} />

Oprócz tych dwóch podejść, można również przekazać argumenty do funkcji, która jest zdefiniowana jako funkcja curry ' ego.

handleClick = (id) => () => {
    console.log("Hello, your ticket number is", id)
};

<button onClick={this.handleClick(id)} />
 2
Author: Umair Ahmed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-04-26 11:05:02

Użycie funkcji strzałki:

Musisz zainstalować stage-2:

Npm install 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
Author: SM Chinna,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-11 10:31:22

Są 3 sposoby, aby sobie z tym poradzić: -

  1. Bind metodę w konstruktorze jako: -

    export class HeaderRows extends Component {
       constructor() {
           super();
           this.handleSort = this.handleSort.bind(this);
       }
    }
    
  2. Użyj funkcji strzałki podczas tworzenia jako:-

    handleSort = () => {
        // some text here
    }
    
  3. Trzecia droga jest taka:-

    <th value={column} onClick={() => that.handleSort} >{column}</th>
    
 0
Author: Mansi Teharia,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-01 09:00:26

Możesz użyć swojego kodu w następujący sposób:

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

Tutaj e jest dla obiektu event, jeśli chcesz użyć metod eventowych, takich jak preventDefault() w funkcji handle lub chcesz uzyskać wartość docelową lub nazwę, taką jak e.target.name.

 0
Author: Bankim Sutaria,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-04-27 03:42:14

Uznałem rozwiązanie przekazania param jako atrybutu tagu za całkiem rozsądne.

Jednak ma ograniczenia:

  • nie działa poprawnie, gdy element listy ma inne znaczniki (stąd event.cel może być inny niż zamierzony)
  • Param może być tylko ciągiem znaków. Wymaga serializacji i deserializacji.

Dlatego wymyśliłem tę bibliotekę: react-event-param

It:

  • rozwiązuje problem dzieci, poszukując needed atrybut in parents whenever needed
  • automatycznie serializuje i deserializuje param
  • zawiera logikę ustawienia i uzyskania. Nie trzeba zadzierać z nazwami param

Przykład użycia:

import { setEventParam, getEventParam } from "react-event-param";

class List extends Component {
  onItemClick = e => {
    const index = getEventParam(e.target);
    // Do something with index
  };

  render() {
    return (
      <ul>
        {this.props.items.map((itemText, index) => (
          <li
            key={index}
            {...setEventParam(index)}
            onClick={this.onItemClick}
          >
            {{ itemText }}
          </li>
        ))}
      </ul>
    );
  }
}

export default List;
 0
Author: sneas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-08-14 12:21:24

Było wiele kwestii związanych z wydajnością, wszystko w próżni.
Problem z tą obsługą polega na tym, że trzeba je curry, aby włączyć argument, którego nie można nazwać w rekwizytach.
Oznacza to, że komponent potrzebuje obsługi dla każdego klikalnego elementu. Załóżmy, że dla kilku przycisków to nie jest problem, prawda?
Problem pojawia się, gdy obsługujesz dane tabelaryczne z dziesiątkami kolumn i tysiącami wierszy. Tam można zauważyć wpływ stworzenie tylu opiekunów.

Prawda jest taka, że potrzebuję tylko jednego.
Ustawiłem obsługę na poziomie stołu (lub UL lub OL...po kliknięciu mogę stwierdzić, która Komórka została kliknięta, używając danych dostępnych od zawsze w obiekcie event:
nativeEvent.target.tagName
nativeEvent.target.parentElement.tagName 
nativeEvent.target.parentElement.rowIndex
nativeEvent.target.cellIndex
nativeEvent.target.textContent

Używam pól tagname, aby sprawdzić, czy kliknięcie nastąpiło w prawidłowym elemencie, na przykład ignoruj kliknięcia w stopkach ot.
RowIndex i cellIndex podają dokładną lokalizację klikniętej komórki.
Textcontent to tekst klikniętej komórki.

W ten sposób nie muszę przekazywać danych komórki do opiekuna, on może ją samoobsługiwać.
Jeśli potrzebowałem więcej danych, danych, które nie mają być wyświetlane, mogę użyć atrybutu dataset lub ukrytych elementów.
Dzięki prostej nawigacji DOM wszystko jest pod ręką.
To było używane w HTML od zawsze, ponieważ komputery były znacznie łatwiejsze do bog.

 0
Author: Juan Lanus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-11-13 23:06:54

Wystarczy użyć funkcji strzałki, aby przekazać wartość.

<button onClick={() => this.props.onClickHandle("StackOverFlow")}>

Upewnij się, że używasz ()=>, w przeciwnym razie metoda click zostanie wywołana bez zdarzenia click.

Uwaga: Crash sprawdza domyślne metody

Proszę znaleźć poniżej uruchomiony kod w codesandbox dla tego samego.

React pass value with method

 -1
Author: Ganesh Koilada,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-02-09 05:53:33

Prosta zmiana jest wymagana:

Użycie <th value={column} onClick={that.handleSort} >{column}</th>

Zamiast <th value={column} onClick={that.handleSort} >{column}</th>

 -2
Author: Al Amin Shaon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-01-16 12:25:48