栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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

作为示例,我添加了一个小片段来显示其工作方式

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>

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/381289.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号