美文网首页
组件 props 命名的方式

组件 props 命名的方式

作者: 莫帆海氵 | 来源:发表于2021-01-18 22:35 被阅读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>
      );
    }
    

    相关文章

      网友评论

          本文标题:组件 props 命名的方式

          本文链接:https://www.haomeiwen.com/subject/zbsfzktx.html