gpt4 book ai didi

javascript - 如何将事件处理程序传递给 React 中的子组件

转载 作者:可可西里 更新时间:2023-11-01 02:02:47 24 4
gpt4 key购买 nike

我有一个 <Button />我在 React 中创建的组件抽象出我应用程序中的一些样式。我在两个不同的上下文中使用它——一个提交登录表单,另一个导航到注册页面(将来可能还有其他上下文)。

我想弄清楚如何将事件处理程序从父组件传递到 <Button /> .我想调用onSubmit登录表单的处理程序,但是一个 onClick导航按钮的处理程序。这可能吗?

我试过这样调用组件:

<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)}/>

我还尝试删除箭头函数,这只会导致函数在加载组件时执行:

// 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)}/>

最佳答案

通常,您可以将 onClick 处理程序作为属性传递给您的按钮类。您可以通过简单地为按钮组件定义 propTypes 来制作所需的 Prop 。

例如,我添加了一个小片段来展示它是如何工作的

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>

此外,您通常不会使用按钮的提交方法,您宁愿将收到的数据发送到网络服务,并在收到结果时处理任何更改。提交杀死当前网站并需要重新加载所有内容,而使用 ajax 调用或商店,它可以等待结果,然后根据响应重定向用户

关于javascript - 如何将事件处理程序传递给 React 中的子组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39904795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com