javascript - 如何在ReactJS中的onClick上获取父类组件上的子功能组件方法
问题描述
我有一个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
解决方案
我相信这篇文章可能会对您的问题有所了解: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;
在增量.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”关键字!
- 不需要整个增量子组件