2017-04-19 64 views
1

我現在有一個陣營組成部分......下面的代碼:陣營組件變化從一種類型到另

import React, { PropTypes } from 'react'; 

export default class Message extends React.Component { 
    constructor(props) { 
    super(props); 
    } 
    render() { 

    const { type } = this.props; 

    if (type === 'success') { 
     return (<div>{this.props.msg}</div>); 
    } 
    } 
} 

我需要將其更改爲這種類型的組件:

const Message = props => (
    //Stuff here 
); 


export default Message 

我怎樣才能做到這一點?

+0

更換'const的消息...'和'常量留言= props => props.type ==='成功'?

{props.msg}
:null;' – elmeister

回答

4

如果我沒錯,你只是想創建一個無狀態版本的初始組件。要做到這一點,你把你的lambda函數當作你的渲染函數。例如:

const Message = ({ type, msg }) => (type === 'success') ? <div>{msg}</div> : null 

如果你不舒服ternarys,這是同樣的事情上面(也與解構):

const Message = props => { 
    const { type, msg } = props 
    if(type === 'success'){ 
     return <div>{msg}</div> 
    }else{ 
     return null; 
    } 
} 
+0

正在獲取:錯誤:消息(...):必須返回有效的React元素(或null)。您可能返回了未定義的數組或其他無效對象。 – JakeBrown777

+0

對不起,在第二個例子中忘了其他。 –

1

功能組件基本上是類組件的簡寫,僅定義了render方法。函數的主體基本上是render函數的主體。

const Message = props => { 
    const { type, msg } = props; 

    if (type === 'success') { 
     return (<div>{msg}</div>); 
    }else{ 
     return null; 
    } // :) 
}; 
+0

獲取:錯誤:消息(...):必須返回有效的React元素(或null)。您可能返回了未定義的數組或其他無效對象。 – JakeBrown777