2016-11-23 11 views
0

我有一個reactjs rendermethod,我試圖通過一個函數來設置一個變量,它看起來像這樣(你猜對了,不工作):如何在reactjs中設置渲染變量?

render() { 
     let myVariable='' 

     //this function changes/sets myVariable 
     this.changeMyVariable() 

     return (
      <div>{myVariable}</div> 
     ); 
} 

如何設置了在使用的變量我通過另一個函數渲染,就像上面的例子。我也嘗試使用statevariable,但changeVariable函數運行兩次。

+0

可能你正在追逐一種反模式,並不理解反應的思維方式。 –

回答

8
render() { 
    // assuming 'changeMyVariable' returns a value 
    const myVariable = this.changeMyVariable(); 

    return (
     <div>{myVariable}</div> 
    ); 
} 

其實你可以調用您的JSX本身內部的功能:

<div>{this.changeMyVariable()}</div>

注意:如果this.changeMyVariable()輸出從未改變過基於新的道具,這是更好地計算外render價值(避免重複計算,當組件重新繪製)。

0

儘管您可以在渲染中設置局部變量,但建議使用props以獲得更好的可修改性。

所以,你先在部分 '聲明' 的屬性:

class ExampleComponent extends React.Component { 
    static propTypes = { 
     myVariable: React.PropTypes.string.isRequired, 
    };  
    static defaultProps = { 
     myVariable: 'Default Value' 
    }; 

然後,你渲染這個prop在渲染方法:

render() { 
    return (
     <div>{this.props.myVariable}</div> 
    ); 
} 

要使用此prop當你渲染:

render() { 
    <ExampleComponent myVariable='example'/> 
}