简体   繁体   中英

Functional components inside vs outside of React class

I am wondering what the effects of coupling / nesting a functional component inside a React class component without explicitly passing props to it via params and using this.props via the parent class are. I understand that having a functional component outside of the React class component is easier to test and read, but am curious to know what the exact difference between using this.props vs props via params are in terms of performance / renders.

For example:

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

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

Vs.

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

Both give the same result except when you care about code reusability.

If you care about reusing the Bar function then you better keep it outside the class so you can import it elsewhere.

Example:

If Bar renders a success or warning message. you'll want to keep the same design for all warning messages in the system. Now if every component has its own warning message code, you'll not be able to edit the warning message design easily also you'll have to keep rewriting the same code over and over again .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM