2016-07-08 72 views
1

在幾個組件我有一個函數返回用戶頭像的URL:有沒有辦法在React中創建我自己的幫助函數?

import defaultAvatar from 'assets/images/default-pic.jpg' 

class MyComponent extends Component { 
    userAvatar() { 
    const { profile } = this.props 

    if (profile.has_avatar) { 
     return profile.avatar 
    } else { 
     return defaultAvatar 
    } 
    } 
} 

是有辦法乾式多部件之間的這個功能呢?

+0

如果你可以壓扁你的道具,你可以使用'defaultProps'來爲'profile'指定一個默認值。 –

回答

2

使用默認道具

如果您接受化身爲頂級性能的化身組件,那麼你可以使用默認道具來指定未提供的值。

function Avatar({ avatar }) { 
    return <img src={avatar} />; 
} 

Avatar.defaultProps = { avatar: defaultAvatar }; 

然後從現有的組件中渲染這個新組件。

return (
    <Avatar profile={props.profile} /> 
); 

這樣就可以把一切都聲明,並刪除了has_avatar財產的需要。

作爲一個效用函數

但是,你也可以只撕了直出和小提琴的參數,所以你可以從任何地方調用它。

function getUserAvatar(profile) { 
    if (profile.has_avatar) { 
    return profile.avatar 
    } else { 
    return defaultAvatar 
    } 
} 

然後重寫你的原代碼。

class MyComponent extends Component { 
    userAvatar() { 
    const { profile } = this.props 

    return getUserAvatar(profile); 
    } 
} 

作爲一個高階組件

這也將有可能實現這是一個高階組件。

function WithAvatar(Component) { 
    return function(props) { 
    const { profile } = props; 
    const avatar = getUserAvatar(profile); 

    return <Component avatar={avatar} {...props} />; 
    }; 
} 

這將允許您用WithAvatar組件包裝任何現有組件。

function Profile(props) { 
    const { profile, avatar } = props; 
    return (
    <div> 
     <img src={avatar.src} /> 
     <span>{profile.name}</span> 
    </div> 
); 
} 

const ProfileWithAvatar = WithAvatar(Profile); 

render(
    <ProfileWithAvatar profile={exampleProfile} />, 
    document.getElementById('app') 
); 

傳遞profile爲道具到外分量使WithAvatar處理它並選擇正確的化身,然後它向下傳遞爲道具給被包裝的組件。

2

如果你已經使用了React.createClass的方法,你可以使用mixins來跨組件共享代碼。由於您使用ES6方法,你可以檢出肝卵圓細胞(高位成分)

參考:https://gist.github.com/sebmarkbage/ef0bf1f338a7182b6775

+2

可能值得一提的是,React團隊正在將文檔和示例轉換爲使用類,以最終廢棄mixin和'createClass',因此HOC可能是最佳選擇。 –

相關問題