【问题标题】:Is it a good practice to use getter to render another component inside React component?使用 getter 在 React 组件中渲染另一个组件是一种好习惯吗?
【发布时间】:2019-03-13 12:53:56
【问题描述】:

在某些情况下,getter 方法变得很方便。但是使用 getter 方法来渲染 React 组件或整个 DOM 呢?为此目的使用经典方法而不是吸气剂不是更好吗?为什么?

我有一种感觉,在这方面有些不妥,但我也知道这可能是关于作者的感受。

所以问题是这是否是一般的好方法?或者你的喜好是什么?

class Attachment extends React.Component {

  get file() {
    return this.props.fields.File;
  }
  get label() {
    return this.props.fields.Label;
  }

  // I'm asking about these 2 getters below this comment

  get editableAttachment() {
    return <SomeComponent field={this.label} />;
  }

  get attachment() {
    return (
      <a
        href={this.file && this.file.value && this.file.value.src}
        target="_blank"
      >
        {(this.label && this.label.value)}
      </a>
    );
  }

  render() {
    return (
      <div className="ui-some-component">
        {this.props.isPageEditing ? this.editableAttachment : this.attachment}
      </div>
    );
  }
}

提前谢谢你。

【问题讨论】:

  • “或者你的喜好是什么?”你说。那么答案是:这取决于您自己的喜好。

标签: javascript reactjs getter react-component


【解决方案1】:

这非常符合消费者的口味,我相信如果你不引入野蛮,任何代码都是好的。

代码越容易理解越好,这也是事实。对于不知道我的代码的人,我会尽量让代码简单易读。

另一方面,我尝试使组件尽可能简单和具有代表性。

也许这将是您自己使用“我的风格指南”的代码示例:

const Attachment = ({ isPageEditing, fields }) => {
  const { file, label } = fields;

  const attachment = isPageEditing ? (
    <SomeComponent field={fields.label} />
  ) : (
    <a href={file && file.value && file.value.src} target="_blank">
      {label && label.value}
    </a>
  );

  return <div className="ui-some-component">{attachment}</div>;
};

希望对你有帮助 最好的

【讨论】:

    【解决方案2】:

    我认为这取决于偏好。与更基本的if x do this, if y do that 渲染相比,延迟计算不会有任何好处——两者都必须完成。

    我的两分钱是保持组件简单易读。为每个条件跳一个类会使下一个开发人员变得更加困难。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-02
      • 2017-06-05
      • 2022-12-04
      • 1970-01-01
      • 2018-01-26
      • 2023-02-15
      • 2017-09-17
      • 2021-01-20
      相关资源
      最近更新 更多