React经典面试题 附详细答案(23年8月)

本文详细解释了React中的组件生命周期、setState、受控/非受控组件、key属性、事件处理、Context、组件间通信、性能优化工具以及高级概念如Hooks和代码分割。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. React中的组件生命周期有哪些?
    答:React中的组件生命周期包括挂载阶段、更新阶段和卸载阶段。具体的生命周期方法有:
  • 挂载阶段:constructor、render、componentDidMount
  • 更新阶段:render、componentDidUpdate
  • 卸载阶段:componentWillUnmount
  1. React中的setState是同步还是异步的?
    答:setState方法是异步的。React会将多个setState调用合并成一个调用,以提高性能。如果需要在setState之后立即获取更新后的状态,可以使用回调函数作为setState的第二个参数。

  2. React中的受控组件和非受控组件有什么区别?
    答:受控组件是由React控制其状态的组件,通过props接收和更新数据。非受控组件是由DOM自身控制状态的组件,通过ref来获取和更新数据。

  3. React中的key属性有什么作用?
    答:key属性用于帮助React识别列表中的每个元素的唯一性,以提高性能。在列表更新时,React会使用key来判断哪些元素被添加、删除或修改。

  4. React中的事件处理有哪些方式?
    答:React中的事件处理可以通过以下方式:

  • 在JSX中直接使用事件处理函数,如onClick、onChange等。
  • 使用事件监听器,如addEventListener。
  • 使用第三方库,如React Router提供的Link组件。
  1. React中的条件渲染有哪些方式?
    答:React中的条件渲染可以通过以下方式:
  • 使用if语句或三元表达式在render方法中进行条件判断。
  • 使用&&运算符进行条件渲染。
  • 使用switch语句进行多个条件的渲染。
  1. React中如何处理表单输入?
    答:React中可以通过onChange事件处理表单输入。通过事件处理程序获取输入的值,并将其保存到组件的状态中。

示例代码:

class MyForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: ''
    };
  }

  handleChange(event) {
    this.setState({ inputValue: event.target.value });
  }

  handleSubmit(event) {
    event.preventDefault();
    console.log('Input value:', this.state.inputValue);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit.bind(this)}>
        <input type="text" value={this.state.inputValue} onChange={this.handleChange.bind(this)} />
        <button type="submit">Submit</button>
      </form>
    );
  }
}
  1. React中的Context是什么?
    答:Context是React提供的一种跨组件传递数据的机制。它可以避免通过props一层层传递数据,使组件之间的数据共享更加方便。

示例代码:

const MyContext = React.createContext();

class ParentComponent extends React.Component {
  render() {
    return (
      <MyContext.Provider value="Hello from ParentComponent">
        <ChildComponent />
      </MyContext.Provider>
    );
  }
}

class ChildComponent extends React.Component {
  render() {
    return (
      <MyContext.Consumer>
        {value => <div>{value}</div>}
      </MyContext.Consumer>
    );
  }
}
  1. React中如何进行组件间的通信?
    答:React中可以通过props、Context和事件等方式进行组件间的通信。props用于父子组件之间的通信,Context用于跨组件传递数据,事件用于子组件向父组件通信。

  2. React中的虚拟DOM是什么?
    答:虚拟DOM是React中的一种内存中的表示,它是对真实DOM的轻量级抽象。React使用虚拟DOM来提高渲染性能,通过比较虚拟DOM的差异来最小化对真实DOM的操作。

  3. React中的Fragment是什么?
    答:Fragment是React提供的一种组件,用于在不添加额外节点的情况下,将多个子元素分组并返回。它可以帮助减少不必要的DOM嵌套。

示例代码:

class MyComponent extends React.Component {
  render() {
    return (
      <React.Fragment>
        <div>Child 1</div>
        <div>Child 2</div>
        <div>Child 3</div>
      </React.Fragment>
    );
  }
}
  1. React中的错误边界是什么?
    答:错误边界是一种React组件,用于捕获并处理其子组件中的JavaScript错误。它可以防止错误的传播,提供优雅的错误处理机制。

示例代码:

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

  componentDidCatch(error, info) {
    this.setState({ hasError: true });
    console.error(error);
  }

  render() {
    if (this.state.hasError) {
      return <div>Oops, something went wrong.</div>;
    }
    return this.props.children;
  }
}

class MyComponent extends React.Component {
  render() {
    if (this.props.shouldThrowError) {
      throw new Error('Error occurred.');
    }
    return <div>No error occurred.</div>;
  }
}

class App extends React.Component {
  render() {
    return (
      <ErrorBoundary>
        <MyComponent shouldThrowError={true} />
      </ErrorBoundary>
    );
  }
}
  1. React中的高阶组件(HOC)是什么?
    答:高阶组件是一种用于复用组件逻辑的模式。它是一个函数,接收一个组件作为参数,并返回一个新的组件。

示例代码:

function withLogging(WrappedComponent) {
  return class extends React.Component {
    componentDidMount() {
      console.log('Component is mounted.');
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  }
}

class MyComponent extends React.Component {
  render() {
    return <div>Hello, World!</div>;
  }
}

const EnhancedComponent = withLogging(MyComponent);
  1. React中的性能优化有哪些?
    答:React的性能优化可以通过以下方式实现:
  • 使用PureComponent或shouldComponentUpdate方法来避免不必要的渲染。
  • 使用memo函数来优化函数组件的渲染。
  • 使用React的代码分割和懒加载来减少初始加载时间。
  • 使用React的虚拟列表或无限滚动来处理大量数据的渲染。
  • 使用React的服务端渲染(SSR)来提高首次加载速度和SEO友好性。
  1. React中的Hooks是什么?
    答:Hooks是React 16.8引入的一种新特性,它可以让函数组件具有类组件的功能。通过使用Hooks,可以在不编写类组件的情况下使用状态、生命周期和其他React特性。

示例代码:

import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `Count: ${count}`;
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
  1. React中的代码分割是什么?
    答:React的代码分割是一种将应用代码拆分为多个小块的技术。它可以帮助减少初始加载时间,并提高应用的性能。

示例代码:

import React, { lazy, Suspense } from 'react';

const MyComponent = lazy(() => import('./MyComponent'));

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

在上面的示例中,使用lazy函数将MyComponent组件进行代码分割。在App组件中,使用Suspense组件来提供一个加载时的占位符,并在需要时异步加载MyComponent组件。

  1. React中的上下文是什么?
    答:上下文是React中一种跨组件层级共享数据的机制。它可以避免通过组件树显式传递props的繁琐过程。

示例代码:

const MyContext = React.createContext();

function MyComponent() {
  return (
    <MyContext.Consumer>
      {value => <div>Value from context: {value}</div>}
    </MyContext.Consumer>
  );
}

function App() {
  return (
    <MyContext.Provider value="Hello, World!">
      <MyComponent />
    </MyContext.Provider>
  );
}

在上面的示例中,使用createContext函数创建了一个上下文对象MyContext。在App组件中,使用MyContext.Provider组件将值传递给MyComponent组件。在MyComponent组件中,使用MyContext.Consumer组件获取上下文的值并进行渲染。

  1. React中的渲染属性模式是什么?
    答:渲染属性模式是一种通过将函数作为组件的属性来实现组件复用的模式。它可以帮助减少重复的代码,并提高组件的灵活性。

示例代码:

function MyComponent({ render }) {
  return <div>{render('Hello, World!')}</div>;
}

function App() {
  return (
    <MyComponent
      render={value => (
        <div>Value from render prop: {value}</div>
      )}
    />
  );
}

在上面的示例中,MyComponent组件通过render属性接收一个函数,并将函数的返回值作为内容进行渲染。在App组件中,通过render属性传递一个函数来定义要渲染的内容。

  1. React中的受控组件和非受控组件有什么区别?
    答:受控组件是由React控制表单元素的值和状态的组件。它通过使用value或checked属性和onChange事件处理程序来实现双向数据绑定。

非受控组件是由DOM本身控制表单元素的值和状态的组件。它使用ref来获取表单元素的值,并且不需要使用value或checked属性和onChange事件处理程序。

示例代码:

// 受控组件
class ControlledComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: '' };
  }

  handleChange(event) {
    this.setState({ value: event.target.value });
  }

  render() {
    return (
      <input
        type="text"
        value={this.state.value}
        onChange={event => this.handleChange(event)}
      />
    );
  }
}

// 非受控组件
class UncontrolledComponent extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  handleSubmit(event) {
    event.preventDefault();
    console.log('Input value:', this.inputRef.current.value);
  }

  render() {
    return (
      <form onSubmit={event => this.handleSubmit(event)}>
        <input type="text" ref={this.inputRef} />
        <button type="submit">Submit</button>
      </form>
    );
  }
}

在上面的示例中,ControlledComponent是一个受控组件,它通过value属性和onChange事件处理程序来控制输入框的值。UncontrolledComponent是一个非受控组件,它使用ref来获取输入框的值,并且不使用value属性和onChange事件处理程序。

  1. React中的错误边界是什么?
    答:错误边界是一种React组件,用于捕获并处理其子组件中的JavaScript错误。它可以防止错误的传播,提供优雅的错误处理机制。

示例代码:

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

  componentDidCatch(error, info) {
    this.setState({ hasError: true });
    console.error(error);
  }

  render() {
    if (this.state.hasError) {
      return <div>Oops, something went wrong.</div>;
    }
    return this.props.children;
  }
}

class MyComponent extends React.Component {
  render() {
    if (this.props.shouldThrowError) {
      throw new Error('Error occurred.');
    }
    return <div>No error occurred.</div>;
  }
}

class App extends React.Component {
  render() {
    return (
      <ErrorBoundary>
        <MyComponent shouldThrowError={true} />
      </ErrorBoundary>
    );
  }
}

在上面的示例中,ErrorBoundary组件捕获并处理了MyComponent组件中的错误。如果MyComponent组件抛出一个错误,ErrorBoundary组件将渲染一个错误消息,否则将渲染MyComponent组件的内容。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一花一world

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值