简体   繁体   中英

How to pass a props to event handler

  • I would like to pass a custom props to the onClick handler.
  • I cannot return an inline function as below, because I will have to later fire redux action creator as part of the handler (async action is not allowed)
onClick={()=>this.handleClick("v")}
  • Using middleware seems an overkill to me..
  • For simplicity purpose, please just ignore the redux part. Just say we can't use inline arrow function like this.

The example code below is just a POC approach that I borrow from input component, where value is an inherited props. I am OK with any props("custom" as I said)

class Test extends React.Component {
    handleClick = (event) => {
        console.log(event.target.value);

    }

    render() {
        return (
            <div>
                <label
                    value="v" 
                    onClick={this.handleClick}
                >
                    TEST Label
                </label>
            </div>
        )

}

I expect console log to output a custom value -- "v"

use mapDispatchToProps to pass action to the components and call it similar to above.

import React from "react";

import { action1 } from "./actions";

const App = ({action1})=> (
  <button onClick={()=>action1("one")}>Click Me</button>
  );

export default connect(null, {action1})(App);

your options are really limited. You should either use the inline arrow function and handle you async whatever problem in some other way or you should find a way to keep your state updated with current value of your label value. If it was an input onChange = {this.handleChange} would do it. this way your code will look like this:

handleClick(){
    const {value} = this.state;
    doSomething(value)
}
updateValue(input){
/*    this.setState({
        value : input
    })*/
    //in your case :
    this.setState({
        value : 'v'
    })
}
render(){
    return(
        <label 
            value= {this.state.value}
            onClick={this.handleClick}
        >Text</label>
    )
}

hope this helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM