加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React中文教程 - Mixins | Traits(代码组合|代码复用机制)

发布时间:2020-12-15 04:56:47 所属栏目:百科 来源:网络整理
导读:代码组合是为了让多个组件之间封分享代码,实现代码复用机制,概念与Python中的Mixins和PHP的Traits相类似。 !DOCTYPE htmlhtmlheadmeta http-equiv='Content-type' content='text/html; charset=utf-8'titleReact | Mixins/titlescript src="build/react.mi

代码组合是为了让多个组件之间封分享代码,实现代码复用机制,概念与Python中的Mixins和PHP的Traits相类似。

<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-type' content='text/html; charset=utf-8'>
<title>React | Mixins</title>
<script src="build/react.min.js"></script>
<script src="build/JSXTransformer.js"></script>
<style>a{color:#00f;cursor:pointer;}a:hover{text-decoration:underline;}</style>
</head>
<body>
<script type="text/jsx">
/** @jsx React.DOM */
var Mixin1 = {
  componentDidMount: function() {
    console.log('Mixin1.componentDidMount()');
  }
};

var Mixin2 = {
  componentDidMount: function() {
    console.log('Mixin2.componentDidMount()');
  }
};


var MyComponent = React.createClass({
  mixins: [Mixin1,Mixin2],render: function() {
    return <div>hello world</div>;
  }
});
var myMyComponent = <MyComponent />;
React.renderComponent(myMyComponent,document.body);
</script>
</body>
</html>
  • 代码共用 - 代码复用
  • 一个组件同时可以添加多个Mixins
  • 每个Mixins不能定义相同名字的函数
  • 但可以定义相同的预定义函数(Lifecycle Method),而相同函数会被顺序执行。shouldComponentUpdate例外,这个函数不能重定义
  • 可以使用外部类库实现Mixins然后提供给React使用


您可以修改并重新发布本文,如果您能留下本文的参考连结,万分谢谢! 如果您对本文存在疑问,欢迎留言或者直接对本文评论,我会在看到的第一时间回复您。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读