Javascript 如何将事件处理程序传递给 React 中的子组件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39904795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to pass an event handler to a child component in React
提问by bgmaster
I have a <Button />
component I've created in React that abstracts out some of the styling in my application. I am using it in two different contexts - one to submit a login form, and the other to navigate to the registration page (and probably other contexts in the future).
我有一个<Button />
在 React 中创建的组件,它抽象出我的应用程序中的一些样式。我在两种不同的上下文中使用它 - 一种用于提交登录表单,另一种用于导航到注册页面(未来可能还有其他上下文)。
I am trying to figure out how to pass the event handlers from the parent component to the <Button />
. I want to call an onSubmit
handler for the login form, but an onClick
handler for the navigation button. Is this possible?
我想弄清楚如何将事件处理程序从父组件传递到<Button />
. 我想onSubmit
为登录表单调用一个处理程序,但onClick
为导航按钮调用一个处理程序。这可能吗?
I have tried calling the component like this:
我试过像这样调用组件:
<Button text={callToAction} style={styles.callToActionButton} onClick={() => FlowRouter.go("Auth")}/>
<Button text="Go!" style={styles.registerButton} onSubmit={() => this.register(this.state.user, this.state.password)}/>
I've also tried removing the arrow function, which just causes the functions to execute when the component is loaded:
我还尝试删除箭头函数,它只会在加载组件时导致函数执行:
// executes event handlers on page load
<Button text={callToAction} style={styles.callToActionButton} onClick={FlowRouter.go("Auth")}/>
<Button text="Go!" style={styles.registerButton} onSubmit={this.register(this.state.user, this.state.password)}/>
回答by Icepickle
In general, you can forward the onClick handler to your button class by passing it as a property. You could this make a required prop by simply defining the propTypes for your button component.
通常,您可以将 onClick 处理程序作为属性传递给您的按钮类。你可以通过简单地为你的按钮组件定义 propTypes 来制作一个必需的道具。
As an example, I added a small snippet that shows how it works
例如,我添加了一个小片段来展示它是如何工作的
var StyledButton = React.createClass({
propTypes: {
// the StyledButton requires a clickHandler
clickHandler: React.PropTypes.func.Required,
// and I guess the text can be seen as required as well
text: React.PropTypes.string.required
},
render: function() {
// as you are sure you have a clickHandler, you can just reference it directly from the props
return <button type="button" onClick={this.props.clickHandler}>{this.props.text}</button>;
}
});
var MyForm = React.createClass({
getInitialState() {
return {
clicked: 0
};
},
click() {
this.setState({clicked: this.state.clicked+1});
alert('ouch');
},
secondClickHandler() {
this.setState({clicked: 0});
alert(':(');
},
render() {
// your parent component simply sets which button
return <fieldset>
<div>
<StyledButton clickHandler={this.click} text="Click me" />
{ (this.state.clicked > 0) && <StyledButton clickHandler={this.secondClickHandler} text="Not again" /> }
</div>
</fieldset>;
}
});
ReactDOM.render(
<MyForm />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
Also, you wouldn't in general use the submit method of a button, you would rather send the data received to a webservice, and handle any changes when the result is received. The submit kills the current website and needs to load everything anew, while with an ajax call, or a store, it can just wait for the result and then redirect the user based on the response
此外,您通常不会使用按钮的提交方法,您宁愿将接收到的数据发送到网络服务,并在接收到结果时处理任何更改。提交杀死当前网站并需要重新加载所有内容,而使用ajax调用或存储,它可以等待结果然后根据响应重定向用户
回答by finalfreq
How we have handled this is we have a button component that renders an a tag and then we have a href prop and a onClick prop you can pass in. If its a link just pass in the href prop to the button and if you are wanting it to execute a function just pass it in an onClick prop and make sure it gets set on the a tag.
我们是如何处理这个问题的,我们有一个渲染 a 标签的按钮组件,然后我们有一个 href 属性和一个 onClick 属性,你可以传入。如果它是一个链接,只需将 href 属性传入按钮,如果你想要它执行一个函数只需将它传递给一个 onClick 道具并确保它被设置在 a 标签上。
In the Button component we also setup a custom onClick function that looks like this:
在 Button 组件中,我们还设置了一个自定义的 onClick 函数,如下所示:
_onClick: function(e) {
if (!this.props.onClick) {
return;
}
this.props.onClick(e);
}
and then on the a tag
然后在 a 标签上
<a href={this.props.href} onClick={this._onClick} />