2017-09-20 41 views
0

()我有一個道具的div,我想根據道具是否比另一道具更大。我在這個特定的組件中有很多事情要做,我擔心我所做的以下所有事情都是不可能的。渲染後可以將兩種proptype加在一起嗎?如果是這樣,我該如何做到這一點?

this.props.currentValue < this.props.newValue不適用於我,但其他一切正常。

我對React很陌生。任何幫助都是極好的!

哦,並且currentValue和newValue的值在單獨頁面上的rates組件內部。

+0

「this.props.currentValue

+0

修好了,謝謝! – ETH

回答

0

this.displayThing行,因爲你要傳遞的,而不是調用功能,使其返回值函數本身的引用,沒有任何渲染。

如果將this.displayThing更改爲this.displayThing(),該行應該按照您的預期進行操作。

但你也有一些不匹配的標籤。 Header組件在同一行上打開並關閉。從縮進看來,它看起來像是指它下面的行被渲染爲Header組件的子元素,但這不是實際發生的事情。

你可以清理一下這樣的:

return (
    <div> 
     <Header heading="Rates"> 
      <div className="value-heading">{currentValue}</div> 
      <div className="value-heading">{newValue}</div>       
     </Header> 

     <div>{this.displayThing()}</div> 
    </div> 
); 

或者,如果你的頭組件沒有提供任何的孩子,可能是這樣的:

return (
    <div> 
     <Header heading="Rates" /> 

     <div className="value-heading">{currentValue}</div> 
     <div className="value-heading">{newValue}</div>       

     <div>{this.displayThing()}</div> 
    </div> 
); 

如果您想要進一步,您還可以刪除一些代碼,並通過將displayThing函數定義爲箭頭函數來簡化課程:

取而代之的是:

export class Rates extends Component { 
    constructor(props) { 
     super(props); 
     this.displayThing = this.displayThing.bind(this); 
    } 

    displayThing() { 
     const increase = <div>{this.props.details}</div>; 
     const thing = <div>hi</div>; 
     if (this.props.currentValue < this.props.newValue) { 
      return increase; 
     } else { 
      return thing; 
     } 
    } 

    // ... rest of the class 
} 

可以使displayThing成箭頭功能,擺脫構造的,就像這樣:

export class Rates extends Component { 
    displayThing =() => { 
     const increase = <div>{this.props.details}</div>; 
     const thing = <div>hi</div>; 
     if (this.props.currentValue < this.props.newValue) { 
      return increase; 
     } else { 
      return thing; 
     } 
    } 

    // ... rest of the class 
} 

類的工作原理相同兩種方式,但它節省了幾行代碼。

+0

我不得不削減一些代碼,錯過了一些事情,但你是正確的。添加()到displayThings函數修復它謝謝你! – ETH

相關問題