使用默认道具
如果您接受化身为顶级性能的化身组件,那么你可以使用默认道具来指定未提供的值。
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
处理它并选择正确的化身,然后它向下传递为道具给被包装的组件。
如果你可以压扁你的道具,你可以使用'defaultProps'来为'profile'指定一个默认值。 –