做出反应。如何将道具从onclick传递到函数 [英] React. how to pass props from onClick to function
本文介绍了做出反应。如何将道具从onclick传递到函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是新手,我正在尝试创建一个应用程序,在该应用程序中,我可以单击一个按钮,一个函数将运行倒计时计时器,但是如果我像这样从onclick传递道具以开始函数,则onclick={Begin(pros.subject)}函数将在我单击之前运行。如果我在BEGIN中不带参数地使用onClick,就不会有道具传下去。我怎么才能把它修好呢?谢谢
import React from 'react';
import SubjectForm from './SubjectForm';
const EditSubject=(props)=>{
return(
<div>
<button onClick={begin}>start</button>
</div>)
};
const begin = (props)=> {
console.log(props.subject)
}
const mapStateToProps=()=>{};
export default connect(mapStateToProps)(EditSubject);
此外,有没有办法或技巧从外部函数使用BEGIN函数内部的变量?因此,我可以在BEGIN Function中使用暂停按钮暂停seInterval。
推荐答案
您在此示例中使用的是功能性(无状态)组件。您还可以使用ES6类来表示Reaction组件,函数是类的方法。然后,您可以在代码中将begin
这样的函数作为类方法,这样它们就可以访问像props
这样的类数据成员。
请参阅以下代码:
import React from 'react';
import SubjectForm from './SubjectForm';
class EditSubject extends React.Component {
constructor() {
super();
this.begin = this.begin.bind(this);
}
begin() {
console.log(this.props.subject);
}
render() {
return (
<div>
<button onClick={begin}>start</button>
</div>
);
}
};
const mapStateToProps=()=>{};
export default connect(mapStateToProps)(EditSubject);
如果您的组件有状态和方法,这只是一种最佳实践。使用您的示例中的功能组件,您可以简单地使用以下内容:
const EditSubject=(props)=>{
return(
<div>
<button onClick={() => begin(props)}>start</button> // passing props here
</div>)
};
很简单,对吧?
这篇关于做出反应。如何将道具从onclick传递到函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文