我已汇入不同的文件的组成部分,我想重置我的定时器,如果我点击进口组件的元素。有没有办法来解决这个问题,或者我应该写在单JSX两种成分?
import {SampleComponent} from "../SampleComponent";
<div>
<SampleComponent onClick = {?????????}/>
</div>
你可以做的是在这里,
import {SampleComponent} from "../SampleComponent";
<div onClick={??????}>
<SampleComponent/>
</div>
或者您可以从父组件传递给函数,并添加点击子组件的顶级节点上的事件。
<div>
<SampleComponent onHandleClick={() => ??????}/>
</div>
resetTimerHandler = (timer)=>{
timer = 0; or this.setState({timer: 0}) // how ever you are defining timer
}
render(){
let displayTimer;
this.updateTimer(displayTimer)// However you are updating timer
return(
<SampleComponent onClick={this.resetTimerHandler.bind(this,displayTimer)} />)
不知道你是如何更新计时器我真的不能给一个明确的答案,但你应该能够应用此虚拟代码。
如果你想调用父组件的功能,每当一个事件(如你的情况的onClick
事件)的子组件时,您将需要通过父函数作为道具。下面是它的样子:
class ParentComponent extends React.Component {
handleClick = () => { ... }
render {
return (
<SampleComponent onClick={this.handleClick} />
)
}
}
这是你的SampleComponent将会如何:
class SampleComponent extends React.Component {
render {
return (
<div onClick={this.props.onClick}> //to call the function on whole component
<button onClick={this.props.onClick}>Click Me</button> //to call the function on a specific element
</div>
)
}
}
我所理解从你的问题至今是希望每当click事件上发生(在样品组分)来调用示例组件的功能。
要做到这一点,这是你的SampleComponent
将如何看起来像:
class SampleComponent extends React.Component {
.
.
render() {
handleClick = () => { ... }
return (
<div onClick={this.handleClick}>
...
</div>
)
}
注意:对于这一点,你并不需要添加的onClick父。
这是很难回答你的问题具体没有更多的上下文(等你想要什么定时器复位)。但答案是否定的,你不需要在同一个文件来实现这两个组件。这是基本的反应通过道具就像你试图在你的问题做什么。
下面是一个例子。说你SampleComponent
如下所示:
// SampleComponent.jsx
function SampleComponent({ onClick }) { // the argument is an object full of the props being passed in
return (
<button onClick={(event) => onClick(event)}>Click Me!</button>
);
}
就是用SampleComponent
组件看起来是这样的:
import SampleComponent from '../SampleComponent';
function resetTimer() {
// Add logic to reset timer here
}
function TimerHandler() {
return (
<SampleComponent onClick={() => resetTimer()} />
);
}
现在,当你点击通过button
呈现SampleComponent
中,onClick
处理程序通过从TimerHandler
将被调用。
一个阵营组件上的道具是真的只是传递到一个function
参数:)