Renders a checkbox list that uses a callback function to pass its selected value/values to the parent component.

  • Use React.setState() to create a data state variable and set its initial value equal to the options prop.
  • Create a function toggle that is used to toggle the checked to update the data state variable and call the onChange callback passed via the component’s props.
  • Render a <ul> element and use Array.prototype.map() to map the data state variable to individual <li> elements with <input> elements as their children.
  • Each <input> element has the type='checkbox' attribute and is marked as readOnly, as its click events are handled by the parent <li> element’s onClick handler.

继续阅读 30秒学会 React 片段 – MultiselectCheckbox

Creates an alert component with type prop.

  • Define appropriate CSS styles and animations for the component’s elements.
  • Use the React.setState() hook to create the isShown and isLeaving state variables and set their values to false.
  • Define timeoutId to keep the timer instance for clearing on component unmount.
  • Use the React.setEffect() hook to update the value of isShown to true and clear interval by using timeoutId when component is unmounted.
  • Define closeNotification function to set the component is removed from DOM by displaying fading out animation and set isShown to false via setTimeout().
  • Define the component, which renders the alert component with user defined message and a close button to remove the component from DOM.

继续阅读 30秒学会 React 片段 – Alert

To act upon swipes, pans, and pinhces as well as the other mobile gestures, you can use hammerjs with HostListener decorator, or an event binding,

npm install hammerjs
@HostListener('swiperight')
public swiperight(): void {
  // Run code when a user swipes to the right
}

继续阅读 30秒学会 Angular 片段 – hammerjs-gestures

In certain cases @Input and @Output properties can be named differently than the actual inputs and outputs.

<div 
  pagination 
  paginationShowFirst="true"
  (paginationPageChanged)="onPageChanged($event)">
</div>
@Directive({ selector: '[pagination]'})
class PaginationComponent {
  @Input('paginationShowFirst') 
  showFirst: boolean = true;

  @Output('paginationPageChanged') 
  pageChanged = new EventEmitter();
}

Note: Use this wisely, see StyleGuide recommedation

翻译自:https://www.30secondsofcode.org/angular/s/renaming-inputs-and-outputs

相关链接

To avoid the expensive operations, we can help Angular to track which items added or removed i.e. customize the default tracking algorithm by providing a trackBy option to NgForOf.

So you can provide your custom trackBy function that will return unique identifier for each iterated item.
For example, some key value of the item. If this key value matches the previous one, then Angular won’t detect changes.

trackBy takes a function that has index and item args.

@Component({
  selector: 'my-app',
  template: `
    <ul>
      <li *ngFor="let item of items; trackBy: trackByFn">{{item.id}}</li>
    </ul>
  `
})
export class AppComponent { 
  trackByFn(index, item) {
    return item.id;
  }
}

If trackBy is given, Angular tracks changes by the return value of the function.

Now when you change the collection, Angular can track which items have been added or removed according to the unique identifier and create/destroy only changed items.

继续阅读 30秒学会 Angular 片段 – trackBy in for loops

Renders a Modal component, controllable through events.
To use the component, import Modal only once and then display it by passing a boolean value to the isVisible attribute.

  • Use object destructuring to set defaults for certain attributes of the modal component.
  • Define keydownHandler, a method which handles all keyboard events, which can be used according to your needs to dispatch actions (e.g. close the modal when <kbd>Esc</kbd> is pressed).
  • Use React.useEffect() hook to add or remove the keydown event listener, which calls keydownHandler.
  • Use the isVisible prop to determine if the modal should be shown or not.
  • Use CSS to style and position the modal component.

继续阅读 30秒学会 React 片段 – Modal

Renders a countdown timer that prints a message when it reaches zero.

  • Use object destructuring to set defaults for the hours, minutes and seconds props.
  • Use the React.useState() hook to create the time, paused and over state variables and set their values to the values of the passed props, false and false respectively.
  • Create a method tick, that updates the value of time based on the current value (i.e. decreasing the time by one second).
  • If paused or over is true, tick will return immediately.
  • Create a method reset, that resets all state variables to their initial states.
  • Use the the React.useEffect() hook to call the tick method every second via the use of setInterval() and use clearInterval() to cleanup when the component is unmounted.
  • Use a <div> to wrap a <p> element with the textual representation of the components time state variable, as well as two <button> elements that will pause/unpause and restart the timer respectively.
  • If over is true, the timer will display a message instead of the value of time.

继续阅读 30秒学会 React 片段 – CountDown

Renders a carousel component.

  • Use the React.useState() hook to create the active state variable and give it a value of 0 (index of the first item).
  • Use an object, style, to hold the styles for the individual components.
  • Use the React.useEffect() hook to update the value of active to the index of the next item, using setTimeout.
  • Destructure props, compute if visibility style should be set to visible or not for each carousel item while mapping over and applying the combined style to the carousel item component accordingly.
  • Render the carousel items using React.cloneElement() and pass down rest props along with the computed styles.

继续阅读 30秒学会 React 片段 – Carousel

Renders a star rating component.

  • Define a component, called Star that will render each individual star with the appropriate appearance, based on the parent component’s state.
  • In the StarRating component, use the React.useState() hook to define the rating and selection state variables with the initial values of props.rating (or 0 if invalid or not supplied) and 0.
  • Create a method, hoverOver, that updates selected and rating according to the provided event.
  • Create a <div> to wrap the <Star> components, which are created using Array.prototype.map on an array of 5 elements, created using Array.from, and handle the onMouseLeave event to set selection to 0, the onClick event to set the rating and the onMouseOver event to set selection to the star-id attribute of the event.target respectively.
  • Finally, pass the appropriate values to each <Star> component (starId and marked).

继续阅读 30秒学会 React 片段 – StarRating