首页 > web前端 > js教程 > 正文

React Basics Part 2

DDD
发布: 2024-09-19 06:27:06
原创
771 人浏览过

React Basics Part 2

Here are some more advanced React concepts and terminologies:

12. Context API

The Context API provides a way to pass data through the component tree without having to pass props manually at every level. It is useful for global data like themes, authentication, or user data.

Example:

const ThemeContext = React.createContext('light');

function ThemedButton() {
  return (
    <ThemeContext.Consumer>
      {theme => <button className={theme}>I am styled by {theme} theme!</button>}
    </ThemeContext.Consumer>
  );
}

function App() {
  return (
    <ThemeContext.Provider value="dark">
      <ThemedButton />
    </ThemeContext.Provider>
  );
}
登录后复制

13. Refs

Refs provide a way to access DOM nodes or React elements created in the render method. It’s often used to directly modify a DOM element or manage focus.

Example:

import { useRef } from 'react';

function TextInputWithFocusButton() {
  const inputEl = useRef(null);

  const onButtonClick = () => {
    inputEl.current.focus();
  };

  return (
    <div>
      <input ref={inputEl} type="text" />
      <button onClick={onButtonClick}>Focus the input</button>
    </div>
  );
}
登录后复制

14. Higher-Order Component (HOC)

An HOC is a function that takes a component and returns a new component. It’s often used to reuse component logic.

Example:

function withLogger(WrappedComponent) {
  return function WithLogger(props) {
    console.log('Rendering component');
    return <WrappedComponent {...props} />;
  };
}

const EnhancedComponent = withLogger(MyComponent);
登录后复制

15. React.memo

React.memo is a higher-order component that helps to optimize performance by memoizing a component. If the props haven't changed, the component will skip re-rendering.

Example:

const MyComponent = React.memo(function MyComponent(props) {
  return <div>{props.text}</div>;
});

登录后复制

16. useReducer Hook

The useReducer hook is an alternative to useState. It’s useful for managing more complex state logic, especially when the state depends on previous values.

Example:

import { useReducer } from 'react';

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <div>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
      <span>{state.count}</span>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
    </div>
  );
}
登录后复制

17. React Fragments

React Fragments let you group a list of children without adding extra nodes to the DOM.

Example:

function Table() {
  return (
    <>
      <tr>
        <td>Row 1</td>
      </tr>
      <tr>
        <td>Row 2</td>
      </tr>
    </>
  );
}

登录后复制

18. Portals

Portals provide a way to render children into a DOM node that exists outside the hierarchy of the parent component.

Example:

import ReactDOM from 'react-dom';

function Modal({ children }) {
  return ReactDOM.createPortal(
    <div className="modal">{children}</div>,
    document.getElementById('modal-root')
  );
}

登录后复制

19. Error Boundaries

Error Boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI.

Example:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children;
  }
}
登录后复制

20. Lazy Loading

React supports lazy loading of components, which means components can be loaded asynchronously when they are required, improving performance for large applications.

Example:

import React, { Suspense } from 'react';

const OtherComponent = React.lazy(() => import('./OtherComponent'));

function MyComponent() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <OtherComponent />
    </Suspense>
  );
}

登录后复制

21. StrictMode

StrictMode is a tool for highlighting potential problems in an application. It doesn’t render any visible UI but checks for issues like deprecated lifecycle methods.

Example:

function App() {
  return (
    <React.StrictMode>
      <MyComponent />
    </React.StrictMode>
  );
}

登录后复制

22. Controlled vs Uncontrolled Components

Controlled Components: Form elements where the value is controlled by React state.

Uncontrolled Components: Form elements where the value is handled by the DOM.

Example of Controlled Component:

function ControlledInput() {
  const [value, setValue] = useState('');

  return (
    <input
      type="text"
      value={value}
      onChange={(e) => setValue(e.target.value)}
    />
  );
}

Example of Uncontrolled Component:

function UncontrolledInput() {
  const inputRef = useRef(null);

  return <input type="text" ref={inputRef} />;
}
登录后复制

23. Prop Drilling

Prop Drilling occurs when data is passed down through multiple levels of components to reach a deeply nested child. This can be avoided by using Context API or state management libraries.

Example of Prop Drilling:

function Grandparent() {
  const name = "John";
  return <Parent name={name} />;
}

function Parent({ name }) {
  return <Child name={name} />;
}

function Child({ name }) {
  return <p>{name}</p>;
}
登录后复制

24. Rendering Lifecycle

React components have a lifecycle with methods that are invoked at different stages, such as mounting, updating, and unmounting.

Lifecycle methods (class components):

  1. - componentDidMount
  2. - componentDidUpdate
  3. - componentWillUnmount

Example:

class MyComponent extends React.Component {
  componentDidMount() {
    console.log('Component mounted');
  }

  componentDidUpdate() {
    console.log('Component updated');
  }

  componentWillUnmount() {
    console.log('Component will unmount');
  }

  render() {
    return <div>Hello!</div>;
  }
}

登录后复制

25. useRef Hook

The useRef hook is used to persist values across renders without causing a re-render. It’s commonly used for accessing DOM elements or storing mutable values.

Example:

function Timer() {
  const countRef = useRef(0);

  useEffect(() => {
    const intervalId = setInterval(() => {
      countRef.current += 1;
      console.log(countRef.current);
    }, 1000);

    return () => clearInterval(intervalId);
  }, []);

  return <p>Check the console to see the timer.</p>;
}
登录后复制

These additional concepts will help you deepen your understanding of React and tackle more advanced scenarios!

以上是React Basics Part 2的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!