如何从reactjs中的按钮向函数传递props

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

本文关键字:函数 props 按钮 reactjs      更新时间:2023-09-26

我想在reactJS中使用事件处理程序将用户重定向到另一个路由,但我还没有弄清楚如何将其道具传递给事件处理程序函数。

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

这就是我的事件监听器的样子

onOpenChallenge: function(url) {
    window.location.href = url;
}

问题是,每当我加载页面时,该函数就会自动启动,而不是等待事件处理程序,我还会得到以下错误。

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

您需要注意以下事项:

  1. 事件处理程序需要映射到一个函数:
<button onClick={this.onChallengeButtonClicked}>Start</button>
  1. 您需要告诉每个按钮对应的项目:
<button item={item} onClick={this.onChallengeButtonClicked}>Start</button>
  1. 事件处理程序函数可以通过访问事件参数来检测单击了哪个按钮项:
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')
)