当前位置:  首页>> 技术小册>> ReactJS面试指南

答案:
React 中进行组件间通信主要有三种方式:props、回调函数和全局状态管理。

第一种方式是通过 props 进行组件间通信。在 React 中,父组件可以向子组件传递数据和回调函数,子组件可以通过 props 属性接收这些数据和回调函数。例如:

  1. class ParentComponent extends React.Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = { message: 'Hello, world!' };
  5. this.handleClick = this.handleClick.bind(this);
  6. }
  7. handleClick() {
  8. this.setState({ message: 'Hello, React!' });
  9. }
  10. render() {
  11. return (
  12. <div>
  13. <ChildComponent message={this.state.message} onClick={this.handleClick} />
  14. </div>
  15. );
  16. }
  17. }
  18. function ChildComponent(props) {
  19. return (
  20. <div>
  21. <p>{props.message}</p>
  22. <button onClick={props.onClick}>Click me</button>
  23. </div>
  24. );
  25. }

第二种方式是通过回调函数进行组件间通信。在 React 中,子组件可以向父组件传递数据和回调函数,父组件可以通过 props 属性接收这些回调函数并执行相应的操作。例如:

  1. class ParentComponent extends React.Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = { message: '' };
  5. this.handleChildClick = this.handleChildClick.bind(this);
  6. }
  7. handleChildClick(message) {
  8. this.setState({ message: message });
  9. }
  10. render() {
  11. return (
  12. <div>
  13. <ChildComponent onClick={this.handleChildClick} />
  14. <p>{this.state.message}</p>
  15. </div>
  16. );
  17. }
  18. }
  19. function ChildComponent(props) {
  20. function handleClick() {
  21. props.onClick('Hello, parent!');
  22. }
  23. return <button onClick={handleClick}>Click me</button>;
  24. }

第三种方式是通过全局状态管理进行组件间通信。在 React 中,可以使用 Redux、MobX 等第三方库来实现全局状态管理。这些库通常使用单一状态树来管理应用程序的状态,并使用发布-订阅模式来实现组件间通信。例如:

  1. import { createStore } from 'redux';
  2. const initialState = { message: '' };
  3. function reducer(state = initialState, action) {
  4. switch (action.type) {
  5. case 'SET_MESSAGE':
  6. return { message: action.payload };
  7. default:
  8. return state;
  9. }
  10. }
  11. const store = createStore(reducer);
  12. class ParentComponent extends React.Component {
  13. constructor(props) {
  14. super(props);
  15. this.state = store.getState();
  16. this.unsubscribe = null;
  17. }
  18. componentDidMount() {
  19. this.unsubscribe = store.subscribe(() => {
  20. this.setState(store.getState());
  21. });
  22. }
  23. componentWillUnmount() {
  24. this.unsubscribe();
  25. }
  26. render() {
  27. return (
  28. <div>
  29. <ChildComponent />
  30. <p>{this.state.message}</p>
  31. </div>
  32. );
  33. }
  34. }
  35. function ChildComponent() {
  36. function handleClick() {
  37. store.dispatch({ type: 'SET_MESSAGE', payload: 'Hello, parent!' });
  38. }
  39. return <button onClick={handleClick}>Click me</button>;
  40. }

该分类下的相关小册推荐: