【问题标题】:Functional components inside vs outside of React classReact 类内部与外部的功能组件
【发布时间】:2020-04-27 10:15:25
【问题描述】:

我想知道在 React 类组件中耦合/嵌套功能组件而不通过参数显式传递道具并通过父类使用 this.props 的效果是什么。我知道在 React 类组件之外拥有一个功能组件更容易测试和阅读,但我很想知道通过参数使用 this.propsprops 在性能/渲染方面的确切区别。

例如:

class Foo extends React.Component {
  bar = () => { return (<p>{this.props.baz}</p>) }

  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
      {this.bar()}
    )
  }
}

对比

class Foo extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
      <Bar baz={'foobar'}
    )
  }
}
function Bar(props) {
  return <p>{props.baz}</p>
}

【问题讨论】:

    标签: javascript reactjs react-functional-component


    【解决方案1】:

    除非您关心代码的可重用性,否则两者都会给出相同的结果。

    如果您关心重用Bar 函数,那么您最好将其保留在class 之外,这样您就可以在其他地方使用import

    示例:

    如果Bar 呈现successwarning 消息。您需要为系统中的所有警告消息保持相同的设计。 现在,如果每个component 都有自己的警告消息代码,您将无法轻松编辑警告消息设计,而且您必须一遍又一遍地重写相同的代码

    【讨论】:

    • 我知道在视觉效果方面的结果是一样的,但我很好奇是否说名称道具更新,但巴兹没有。 Bar 会在这两种情况下重新渲染吗?
    • 在这种情况下,默认情况下是的,它会重新渲染,但您可以使用 react memo 调整此行为 reactjs.org/docs/react-api.html#reactmemo @tomato
    猜你喜欢
    • 2020-12-10
    • 2021-08-06
    • 2021-08-30
    • 2019-08-06
    • 2021-07-13
    • 2019-12-08
    • 2020-01-25
    • 1970-01-01
    • 2020-11-01
    相关资源
    最近更新 更多