简体   繁体   中英

Stateless functional component vs. additional render method in a stateful component?

As a really basic example, imagine I wanted to render a div containing some text outside of my render() method. Which of these options would be better?

class StatefulComponent extends Component {
  ...

  render() {
    return (
      {this.renderTextDiv(this.state.text)}
    )
  }

  renderTextDiv(text) {
    return <div>text</div>
  }
}

or

class StatefulComponent extends Component {
  render() {
    return (
      <TextDiv text={this.state.text} />
    )
  }
}

function TextDiv({text}) {
  return <div>{text}</div>;
}

Or would you completely pull the stateless component into its own class? Or does it just not matter at all? Does one make testing easier? Readability? Any differences at all?

It does not make any difference in terms of what is being displayed. However, it definitely changes the structure and readability of the code.

For myself, I try to divide the structure into as much Components as possible, and so does Thinking in react suggests. However, if you think that the element does not structurally differ from its parent component and thus does not deserve its own separate component but you require some readability and re-usability, the top code works.

The first one looks more concise in my opinion. You could render html in methods if it's not a big code, or, just a conditional rendering inside the component. Whenever you have some html rendering with a big structure and some functionality, it is always good to separate it into its proper component, because you probably would reuse this code later. Again: If it's not a big code or functionality, it's ok to use html rendering inside a method.

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