React component Mode

Source: Internet
Author: User


Component development is the core of react, and learning how to use and organize them helps you create good design structures.



What is a component?



According to React's official website, the explanation is as follows:



Components can split your UI view independently, they are reusable, separate units.



Similar to functions, the input source received by a component in react is called props, and the react element is returned. The react element is a description of the UI interface. You can tell react the UI interface you expect, and the rest of the work can be handed to react for processing.



We take a taxi analogy, when you tell the driver where you want to go, the driver will send you safely to your destination as you wish. Instead of driving yourself in person.



Component Api ' s



What are the React APIs? React has a total of 5 major APIs they are:



1.render



2.state



3.props



4.context



5.life Cycle Events



The component has a state component and a stateless component, and the state component uses the Api,render state and life cycle events that can be controlled. The stateless component uses the render props context.



Component Design patterns, you can separate your data and logical layers, and differentiate your components by their responsibilities. You can create reusable components that can create more complex UI attempts. This is extremely important for building apps.



In component design mode we can divide the components into:



1. Container components



2. Display-Type components



3. High-order components



4.render Callback



Container components:



The container component is used to fetch the data and render the sub-components below him, which is the container component.



The container component can be either your data layer or the business logic layer, and you are using the stateful API. Through life cycle functions you can connect to your state management library, such as Redux or flux. Container components can pass data and callback functions to subcomponents. In the Render method of the container component, build your UI attempt by presenting a combination of components. Because container components are stateful, you need to use class to declare your components instead of using functional components.



In the following example, there is a class component named greeting, which has the state, life cycle function, and render function.


 
class Greeting extends React.Component {
  constructor() {
    super(); this.state = {
      name: "",
    };
  }

  componentDidMount() { // AJAX this.setState(() => { return {
        name: "William",
      };
    });
  }

  render() { return ( <div>
        <h1>Hello! {this.state.name}</h1>
      </div>  );
  }
}


This component is a class component with status. In order for the greeting component to become a container-type component, we need to split the UI into a display-type component. As follows:



Display-Type components:



Display components take advantage of, Props,render,context (stateless API s)


const GreetingCard = (props) => { return ( <div>
      <h1>Hello! {props.name}</h1>
    </div>  )
}


The container component passes data and callback functions through props to the display component. The business logic is packaged together through the container component and the presentation component, and the group synthesizes the new components.


const GreetingCard = (props) => { return ( <div>
      <h1>{props.name}</h1>
    </div>  )
}

class Greeting extends React.Component {
  constructor() {
    super(); this.state = {
      name: "",
    };
  }

  componentDidMount() { // AJAX this.setState(() => { return {
        name: "William",
      };
    });
  }

  render() { return ( <div>
       <GreetingCard name={this.state.name} />
      </div>  );
  }
}


As the example above, we removed the tag element and put him in a stateless display component. This is, of course, a very simple example, but the principle is the same in complex app applications.



High-order components:



A higher-order component, which takes a component as a parameter, and returns a new component.



Higher-order components can provide data to any number of components and effectively reuse business logic. It's a powerful pattern. For example, in React-router and Redux, in React-router you can use Widthrouter () to inherit the method and pass it to your component via props. In redux you can connect to your actions.


import {withRouter} from 'react-router-dom';

class App extends React.Component {
  constructor() {
    super(); this.state = {path: ''}
  }
  
  componentDidMount() {
    let pathName = this.props.location.pathname; this.setState(() => { return {
        path: pathName,
      }
    })
  }
  
  render() { return ( <div>
        <h1>Hi! I'm being rendered at: {this.state.path}</h1>
      </div>
    )
  }
}

export default withRouter(App);


As in the example above, we update the status with This.props.location.pathname. Wrap the component with the Withrouter method. Now our component can come out by props React-rouoter method This.props.location.pathname;






Render Callbacks



Similar to higher-order components, render callbacks or render props are used to reuse the group price logic. There are several reasons and advantages that you can try to use the render callbacks when more developers tend to reuse business logic for higher-order components. Render callsbacks can effectively reduce naming conflicts and clearly show the source of logic.


 
class Counter extends React.Component {
  constructor(props) {
    super(props); this.state = {
      count: 0,
    };
  }

  increment = () => { this.setState(prevState => { return {
        count: prevState.count + 1,
      };
    });
  };

  render() { return ( <div onClick={this.increment}>{this.props.children(this.state)}</div>  );
  }
}

class App extends React.Component {
  render() { return ( <Counter> {state => ( <div>
            <h1>The count is: {state.count}</h1>
          </div>  )} </Counter>  );
  }
}


In the Render method of the Counter class, the This.props.children is embedded and passed in as a this.state parameter. In the app class we can wrap our components in counter to handle the counter logic. So he can handle the state from the counter.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.