如何考虑在 React 中的类组件内部和类外部定义功能组件?

Abr*_*rar 2 javascript reactjs react-component

考虑在 React 中定义函数式组件的以下三个地方 -

  1. 在类内部(在 render 方法之外)
  2. 在类内(在 render 方法内)
  3. 课外

在下面的示例代码,funcComponent1funcComponent2funcComponent3在三个不同的位置限定。我如何考虑何时在这 3 个位置中的任何一个定义功能组件?

import React, { Component } from 'react';


const FuncComponent1 = (props) => {
  return (
    <p>{props.name}</p>
  )
}

class TestComponent extends Component {

  constructor(props){
    super(props);
    this.state = {
      name: "JavaScript"
    }
  }


  FuncComponent2 = (text) => {
    return (
      <p>{text}, {this.state.name}</p>
    )
  }


  render(){

    const FuncComponent3 = (props) => {
      return (
        <p>{props.text}, {this.state.name}</p>
      )
    }

    return (
      <div>
        <FuncComponent1 name={'Abrar'} text={'Hello World'}/>
        <FuncComponent3 text={"HEllo World"}/>
      </div>
    )
  }

}

export default TestComponent;
Run Code Online (Sandbox Code Playgroud)

Shu*_*tri 5

您必须避免使用,functional component inside of render因为它们将在每次渲染时重新创建。

就使用functions that return JSX inside Class component但在渲染之外的情况而言,当您想使用类的状态或道具来呈现 JSX 内容但对特定类非常特定的内容时,您可以这样做

functional component outside of React component当同一个组件可以在多个地方使用时,A是最有利的,因此将 props 传递给它并渲染它是有意义的。