react创建组建的四种方式
原由:写这篇文章主要是为了增强自己的记忆,同时也是为了分享一下我们常用的创建组建的方法,主要是四种 叙述: 我们在用 一、createClassvar React = require("react"); var FirstComponent = React.createClass({ propTypes: { name: React.PropTypes.string //属性校验 (string,number,bool,func,array,object...... ) },getDefaultProps: function() { return { name: 'Mary' }; // 初始化props },getInitialState: function() { return {count: this.props.initialCount}; //初始化props },handleClick: function() { //..... },render: function() { return <h1>Hello,{this.props.name}</h1>; } }); module.exports = FirstComponent;
二、component es6语法堂import React from 'react'; class FirstComponent extends React.Component { constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.state = { count: props.initialCount }; } static propTypes = { name: React.PropTypes.string } statice props = { name: 'Mary' } handleClick() { //点击事件的处理函数 } render() { return <h1 onClick={this.handleClick}>Hello,{this.props.name}</h1>; } } export default FirstComponent;
三、PureComponet上面的方法中都不是纯函数的构造,因为 class CounterButton extends React.PureComponent { constructor(props) { super(props); this.state = {count: 1}; } render() { return ( <button color={this.props.color} onClick={() => this.setState(state => ({count: state.count + 1}))}> Count: {this.state.count} </button> ); } }
四、Stateless Functional Component上面提到的方法都包含了内部有交互和状态的复杂的组建,如果组建本身就是用来展示的,那么就可以用stateless的方法来创建组建。 import React from 'react'; const Button = ({day,increment}) => { return ( <div> <button onClick={increment}>Today is {day}</button> </div> ) } Button.propTypes = { day: PropTypes.string.isRequired,increment: PropTypes.func.isRequired,} export default Button;
以上就是四种创建组建的方式,来点个人的建议吧!
最后大家可以根据自己的喜欢以及项目的要求选择一种方式来进行组建的创建,方便自己的记忆,也供大家参考使用,同时也来提一下更好的方法。 参考: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- c# – 如何通过网址检查网络服务器上是否存在文件?
- table下的表格实现双击变为文本框,利用ajax提交表单
- c# – 使用Newtonsoft.Json反序列化DbGeometry
- PostgreSQL问题分析1:时间线不一致
- 学习TDD(4)--实例2:基于ZooKeeper的服务器注册和探测类[实
- nosql – 在Cassandra中建立M:M关系的替代方法是什么?
- react-native试玩(12)-iOS中导航栏
- iphone – 没有架构来编译(ARCHS = arm6 arm7,VALID_ARCHS
- 混合开发的大趋势之一React Native Props (属性)
- ruby-on-rails – 在Ruby中有一种方法可以告诉方法定义在哪