使用默認道具
如果您接受化身爲頂級性能的化身組件,那麼你可以使用默認道具來指定未提供的值。
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'指定一個默認值。 –