Chapter 1: The first React Web application

The React component

The React component is an ES6 class that inherits the React.componentclass. Render () is the only method required by the React component, which returns the content rendered to the page.

class ProductList extends React.Component {
  render() {
    return (
      <div className='ui unstackable items'>
        Hello, friend! I am a basic React component.
      </div>); }}Copy the code

ES6 introduces class declaration syntax. ES6 classes are the syntactic sugar of JavaScript’s prototype-based inheritance model.

There are two ways to declare the React component:

  • ES6 classes;
  • Import and usecreateReactClass()methods
import createReactClass from 'create-react-class';

const HelloWorld = createReactClass({
    render() { return(<p>Hello, world!</p>)}})Copy the code

JSX and Babel

  • JSX: JavaScript extension syntax, HTML-like syntax, which is compiled into native JavaScript and eventually rendered as HTML displayed in the browser.
// JSX
<div className='ui items'>
  Hello, friend! I am a basic React component.
</div>

// Compile to JavaScript
React.createElement('div', {className: 'ui items'},
  'Hello, friend! I am a basic React component.'
)

/ / renders HTML
Copy the code

The browser’s JavaScript parser gets an error when it encounters JSX, an extension of standard JavaScript. So you can have your browser’s JavaScript interpreter use this extension.

  • Babel: JavaScript translator that translates ES6 to ES5 Compile JSX to vanilla (native) ES5 JS; This is done by setting the Type attribute
// 'type="text/ Babel "' indicates that Babel is required to handle the loading of this script, and data-plugins specify a special 'Babel' plug-in to use
<script
  type="text/babel"
  data-plugins="transform-class-properties"
  src="./js/app.js"
></script>
Copy the code

Three,ReactDOM.render()methods

ReactDOM comes from the React-DOM library and takes two parameters, the first parameter is the component to render (what) and the second parameter is the location of the render component (where) :

ReactDOM.render([what], [where]);

ReactDOM.render(
  <ProductList />.document.getElementById('content'));Copy the code

Data State and Prop

  • stateOwned by the component and called when the component is initializedconstructor()Function defines the initial value, usingthis.setState()Method changes.
  • propsImplementation data flows from parent to child components, which access props through this.props, but cannot modify them. Because the parent component owns the props and supplies the child components, which are not the owners of the props, React supports one-way data flow.

Props can pass primitive types, JavaScript objects, atomic operations, functions, and more, and even React elements and the virtual DOM.

  • When the component’sstateorpropsWhen updated, the component is re-rendered.
/ / the parent component
class ProductList extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      products: [],}; }componentDidMount() {
    this.setState({ products: Seed.products });
  }
  render() {
     const productComponents = this.state.products.map((product) = > (
         <Product
            key={'product-'+product.id}
            id={product.id}
            title={product.title}
          />
    ));
    return (
     <div>{productComponents}</div>); }}/ / child component
class Product extends React.Component {
  render() {
    return (
      <div>{this.props.title} </div>); }}Copy the code

In JSX, the brace is a delimiter that signals to JSX that the content between the braces is a JavaScript expression. Another delimiter is the quotation mark, which is used to represent strings such as id=’1′.

For the Render () function, React automatically binds this to the React component class, so when we write this.props inside the component, it will access the props property on the component.

5. Event transmission

Prop cannot be modified by child components, so when an event is triggered, it needs to be passed to the parent, which makes data changes. Passing functions through props is the standard way that a child component passes events to its parent.

/ / the parent component
class ProductList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      products: [],};this.handleProductUpVote = this.handleProductUpVote.bind(this);
  }
  componentDidMount() {
    this.setState({ products: Seed.products });
  }
  
  handleProductUpVote(productId) {
    console.log(productId + ' was upvoted.');
  }
  render() {
     const productComponents = this.state.products.map((product) = > (
         <Product
            key={'product-'+product.id}
            id={product.id}
            title={product.title}
            onVote={this.handleProductUpVote}
          />
    ));
    return (
     <div>{productComponents}</div>); }}/ / child component
class Product extends React.Component {
  constructor(props) {
    super(props);

    this.handleUpVote = this.handleUpVote.bind(this);
  }
  handleUpVote() {
    this.props.onVote(this.props.id);
  }
  render() {
    return (
      <div onClick={this.handleUpVote}>{this.props.title} </div>); }}Copy the code

Execution steps:

  • OnClick triggers the handleUpVote method;
  • The handleUpVote method tells this.props. OnVote;
  • Execute the parent handleProductUpVote() method;

Update state and immutability

Treat state as immutable and can only be changed using this.setstate (), not to state elsewhere.

// Within ProductList
handleProductUpVote(productId) {
  const nextProducts = this.state.products.map((product) = > {NextProducts is a new array
    if (product.id === productId) {
      return Object.assign({}, product, {// Clone the property without modifying it to the product object
        votes: product.votes + 1}); }else {
      returnproduct; }});this.setState({
    products: nextProducts,
  });
}
Copy the code

Property initializer

The property initializer simplifies React class components and can be used in transform-class-properties of the Babel plugin.

  • Use the arrow function to customize the component method, ensuring that thethisCan bind to the current component and can be deletedconstructor()Function, without manual binding call;
  handleUpVote = () = > (
    this.props.onVote(this.props.id)
  );
Copy the code
  • inconstructor()Define the initial state outside the function
class ProductList extends React.Component {
  state = {
    products: [],
  };
 }
Copy the code