【问题标题】:How to get child function component method on parent class component at onClick in ReactJS如何在ReactJS中的onClick上获取父类组件上的子功能组件方法
【发布时间】:2021-10-18 17:23:04
【问题描述】:

我有一个Parent(基于类的组件)和一个Child(基于函数的组件)。我需要基于函数的组件的方法,当我点击父类组件的(+)按钮时。

  • 我已将子组件导入父组件
  • 我无法处理父组件的点击事件

onClick={ }

这是我的基于父类的组件

import React from "react";
import Increment from "./Increment";

class Timer extends React.Component {

    //State
    state = {
        count: 0
    }
    render() {
        return (
                <div className="top">
                    
                    <span className="display">{this.state.count}</span>
                    <button className="btn btn-primary"  onClick={<Increment  />} >
                        +
                    </button>
                </div>
        )
    }
}
export default Timer

这是我的子函数组件

import React, { Component } from "react";

class Increment extends Component {
    incrementTimer = props => {
        this.setState({ count: props.count + 1 })
    }
}
export default Increment

【问题讨论】:

  • 请更新您的问题或重新整理它以使其更有意义
  • 可以吗? @ShravanDhar
  • 没有。阅读有关功能组件的信息。此外,您不能这样做onClick={&lt;Increment /&gt;onClick 需要一个函数,而不是 React Component

标签: javascript reactjs onclick event-handling parent-child


【解决方案1】:

我相信这篇文章可能会对您的问题有所帮助:Lifting State Up - React Docs。我不建议尝试从组件#2 内部更新组件#1 的状态。 从增量组件中获取增量逻辑,并将其作为父组件的方法。然后将该方法作为道具传递给增量组件。

在 Timer.js 中

import React, { Component } from "react";
import Increment from "./Increment";

class Timer extends Component {
  // The Constructor is necessary for adding the handleIncrement method
  // State should be initialized here as well.
  constructor(props) {
    // super(props) is required on class based component constructors
    super(props);
    this.state = { count: 0 };
    this.handleIncrement = this.handleIncrement.bind(this);
  }

  // This is the method
  handleIncrement() {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      <div className="top">
        <span className="display">{this.state.count}</span>
        {/* handleIncrement is the name of the prop that will be referenced inside
        the Increment.js Component. */}
        {/* this.handleIncrement is the method. */}
        <Increment handleIncrement={this.handleIncrement} />
      </div>
    );
  }
}

export default Timer;

在 Increment.js 中

import React from "react";

// Putting (props) means this component is expecting a prop when
// its been imported and used as <Increment propGoesHere={value} /> in Timer.js
const Increment = (props) => {
  return (
    <button className="btn btn-primary" onClick={props.handleIncrement}>
      +
    </button>
  );
};

export default Increment;

顺便说一句,使用 useState 钩子可以完全避免基于类的组件(因为谁想处理“this”关键字、构造函数和绑定每个方法)。

它看起来像: 在 Timer.js 中

import React, { useState } from "react";

const Timer = () => {
  const [count, setCount] = useState(0);

  const handleIncrement = () => {
    setCount(count + 1);
  };
  return (
    <div className="top">
      <span className="display">{count}</span>
      <button className="btn btn-primary" onClick={handleIncrement}>
        +
      </button>
    </div>
  );
};

export default Timer;
  • 不再需要类来保存状态,现在任何组件都可以保存状态!
  • 不再需要构造函数,不需要绑定方法,不再需要“this”关键字!
  • 不需要整个增量子组件

【讨论】:

    【解决方案2】:

    首先

    <button className="btn btn-primary"  onClick={<Increment  />} >
      +
    </button>
    

    这段特定的代码无法运行。您不能将组件作为函数传递给 onClick。 由于我不知道您的问题的实际应用,我不知道您到底想要实现什么,所以这里只是如何使这些特定组件工作的一个选项。

    import React from "react";
    import Increment from "../components/Increment";
    
    class Timer extends React.Component {
      //State
      state = {
        count: 0,
        mountCounter: false,
      };
    
      increaseCount = () => {
        this.setState({ count: this.state.count + 1, mountCounter: false });
      };
    
      render() {
        return (
          <div className="top">
            <span className="display">{this.state.count}</span>
            <button
              className="btn btn-primary"
              onClick={() => this.setState({ mountCounter: true })}
            >
              +
              {this.state.mountCounter && (
                <Increment increaseCount={() => this.increaseCount()} />
              )}
            </button>
          </div>
        );
      }
    }
    export default Timer;
    
    import React, { Component } from "react";
    
    class Increment extends Component {
      constructor(props) {
        super(props);
      }
      componentDidMount() {
        this.props.increaseCount();
      }
      render() {
        return null;
      }
    }
    export default Increment;
    

    【讨论】:

      猜你喜欢
      • 2020-09-16
      • 2017-01-04
      • 2020-04-16
      • 2021-10-27
      • 2019-11-30
      • 2017-11-24
      • 2016-11-13
      • 2019-11-11
      • 2019-05-19
      相关资源
      最近更新 更多