简体   繁体   中英

how to pass props to a function from a button in reactjs

I want to use an event handler to redirect a user to another route in reactJS but I have not figured out how i can pass down it's props to the event handler function.

<button onClick={ChallengeActions.OpenChallenge(item.title) }>Start<button>

This is what my event listener looks like

onOpenChallenge: function(url) {

    window.location.href = url;
}

The problem is that the function automatically fires up whenever i load the page instead of waiting for the event handler, I also get the following error.

Uncaught Error: Invariant Violation: Expected onClick listener to be a function, instead got type object

You need to take care of the following:

  1. event handlers need to be mapped to a function:
<button onClick={this.onChallengeButtonClicked}>Start</button>
  1. You need to tell each button to which item it corresponds to:
<button item={item} onClick={this.onChallengeButtonClicked}>Start</button>
  1. Event handler function can detect which button item was clicked by accessing the event parameter:
onChallengeButtonClicked: function(event) {
    item = event.currentTarget.item;
    window.location.href = item.title;
}
var ChildComponent = React.createClass({
    render: function () {
        var myCustomValue = "testing this out";
        return (
            <h1 onClick={this.props.customEvent.bind(this, myCustomValue)}>Testing child click function</h1>
        )
    }
});

var ParentComponent = React.createClass({
    customEvent: function (value) {
        // do something wtih value
        alert("you passed " + value);
    },
    render: function () {
        return (
            <ChildComponent customEvent={this.customEvent} />  
        )
    }
});

React.render(
    <ParentComponent customEvent={this.customEvent} />,
    document.getElementById('example')
)

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