React js onClick can't pass value to method

后端 未结 30 1742
北荒
北荒 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:38

    There are nice answers here, and i agree with @Austin Greco (the second option with separate components)
    There is another way i like, currying.
    What you can do is create a function that accept a parameter (your parameter) and returns another function that accepts another parameter (the click event in this case). then you are free to do with it what ever you want.

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

    And you will use it this way:

    
    

    Here is a full example of such usage:

    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 (
          
    {someArr.map(obj => { return (


    ); })}
    ); } } const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement);
    
    
    

    Note that this approach doesn't solve the creation of a new instance on each render.
    I like this approach over the other inline handlers as this one is more concise and readable in my opinion.

    Edit:
    As suggested in the comments below, you can cache / memoize the result of the function.

    Here is a naive implementation:

    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 (
          
    {someArr.map(obj => { return (


    ); })}
    ); } } const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement);
    
    
    

提交回复
热议问题