2016-07-08 67 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可能是最佳选择。 –

相关问题