2017-10-17 54 views
0

我對reactjs真的很陌生,我正在尋找一種簡單的方法來根據狀態更改按鈕的顏色。基本上,我使用reactstrap和我有一個按鈕,我想它的顏色是「次級」,「危險」或「初級」按鈕標籤這樣工作:如何傳遞函數而不是字符串作爲道具到組件

<Button color={String} /> 

我想用一個函數在那裏放一個字符串。基本上這裏是一個小功能:

buttonClassName(radioId) { 
    if (this.state.whatevs.valid === false) 
     return "danger"; 
    if (this.state.whatevs.value === radioId) 
     return "primary"; 
    return "secondary; 
} 

這裏是我要如何使用它:

<Button outline color={() => this.buttonClassName(1)}>blah blah1</Button> 
<Button outline color={() => this.buttonClassName(2)}>blah blah2</Button> 
<Button outline color={() => this.buttonClassName(3)}>blah blah3</Button> 

等的多個按鈕,問題是,在邏輯上反應呵斥我,因爲:

Warning: Failed prop type: Invalid prop `color` of type `function` supplied to `Button`, expected `string`. 

我同意這個觀點,但是我怎樣才能讓這個字符串在不傳遞函數的情況下發生變化,我是否必須從狀態變化出來,它看起來很無聊。當我只有兩種狀態,我可以做這樣的事情:

<Button outline color={(whatevs.valid === false)?"danger":"secondary"}>blah blah1</Button> 

和,要麼不是一個真正的字符串,但它的工作。

+0

變化'顏色= {()=> this.buttonClassName(1)}''到顏色= {this.buttonClassName(1)}' – bennygenel

回答

1

你可以最定義地使用一個函數來返回一個字符串。與您的實現有關的問題是,您通過引用而不是函數的結果傳遞了整個函數

只要做下面這個簡單的修復。這將執行該功能並將所需的字符串返回給<Button>組件。

<Button outline color={this.buttonClassName(1)}>blah blah1</Button> 
<Button outline color={this.buttonClassName(2)}>blah blah2</Button> 
<Button outline color={this.buttonClassName(3)}>blah blah3</Button> 
+0

我可能有一個更大的問題的認識發生反應,我下的印象我不得不使用類似於:「this.buttonClassName = this.buttonClassName(this)」以便能夠從函數內部訪問狀態。所以只要我有這個,你的解決方案將不起作用,現在我評論了這條線,它的工作原理。 – moo

相關問題