簡體   English   中英

如何通過reactjs中的按鈕將props傳遞給函數

[英]how to pass props to a function from a button in reactjs

我想使用事件處理程序將用戶重定向到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. 事件處理函數可以通過訪問event參數來檢測單擊了哪個按鈕項:
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')
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM