Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
170 views
in Technique[技术] by (71.8m points)

reactjs - react class based component vs classes in java

I'm newish to react and I've always thought of a class based component much like I do classes in Java.

Is it correct to compare the two thinking of the class based component and class in Java? In other words, are rendered components like objects in Java where they are an instantiation of the class?

Are there differences?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The one major thing to note as highlighted in the docs is that thinking about OOP (and inheritance to be specific) is that we do not extend classes like you would do in Java.

What does it mean? Lets take this simple example from this answer:

public class ExtendedButton extends Button {
    public ExtendedButton() {
        super();
        styleProperty().bind(Bindings.
                when(buttonState.isEqualTo(ButtonState.CRITICAL)).
                then("-fx-base: red;").
                otherwise(""));

    }
}

An example of this in react would have two main differences.

  • The ExtendedButton would extend React.Component instead of Button
  • Therefore you wont have access to Button.prototype but you can use composition as shown below.

Core Bootstrap Button

class Button extends React.Component {
    render() {
      return (
        <button className=`btn btn-{this.props.btnType}` onClick={this.props.handleClick}>
          { this.props.label} 
        </button>
       )
    }
}

Primary Bootstrap Button

class PrimaryButton extends React.Component {
    render() {
      return (
        <Button btnType="default" handleClick={this.props.handleClick} label={ this.props.label} />
       )
    }
}

This would be the way someone would start writing the bootstrap buttons. This is simplified though and composition can get more interesting as you get to understand it. Consider checking out the whole article in the documentation talking about Composition vs Inheritance


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...