组件 props 命名的方式
2021-01-18 本文已影响0人
莫帆海氵
We recommend naming props from the component’s own point of view rather than the context in which it is being used.
拆分组件前:
function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<img className="Avatar"
src={props.author.avatarUrl}
alt={props.author.name}
/>
</div>
<div className="Comment-text">
{props.text}
</div>
</div>
);
}
拆分组件后
// 这里细分组件的时候
// props 命名为 user 比直接使用来源组件的 author 更好
// user 从 Avatar 组件本身角度考虑命名
function Avatar({ user }) {
return (
<img className="Avatar"
src={user.avatarUrl}
alt={user.name}
/>
);
}
function Comment(props) {
return (
<div className="Comment">
<div className="UserInfo">
<Avatar user={props.author} />
</div>
<div className="Comment-text">
{props.text}
</div>
</div>
);
}