首页 > 其他 > 详细

React组件化编程

时间:2020-03-11 22:05:14      阅读:55      评论:0      收藏:0      [点我收藏+]

1、组件编写方式的注意事项:

  • 组件名首字母必须大写;
  • 虚拟DOM必须只有一个根元素;
  • 虚拟DOM必须有结束标签。

2、两种组件编写方式

  • 简单组件:使用工厂函数,不涉及state值的渲染
    <script type="text/babel">
        function Simple(){
          return <h1>这是工厂函数组件</h1>
        }
        ReactDOM.render(<Simple />,document.getElementById("root")); //注意
    </script>
  • 复杂组件:使用ES6中的class类
  • <script type="text/babel">
        class Mycomponent extends React.Component{
          render(){   //其中render是react的一个关键字
            return (
              <h1>这是一个复杂组件</h1>
            );
          }
        }
        ReactDOM.render(<Mycomponent />,document.getElementById("root"));
    </script>

3、任务:使用复杂组件实现列表功能

技术分享图片
 1 <script type="text/babel">
 2     //3、state相当于VUE中的data
 3     // 做一个遍历列表任务
 4     class MyComponent extends React.Component{
 5       constructor(props){
 6         super(props);
 7         this.state = {
 8           msg:[
 9             赵云,
10             吉吉国王,
11             韩信,
12             露娜,
13           ],
14         }
15       }
16       render(){
17         //取出state中的值
18         var {msg} = this.state;
19         return (
20           <div>
21             <ul>
22               {
23                 msg && msg.map((item,index)=>{
24                   return <li key={index}>{item}</li>
25                 })
26               }
27             </ul>
28           </div>
29         )
30       }
31     }
32     ReactDOM.render(<MyComponent />,document.getElementById("root"));
33 </script>
View Code

 

React组件化编程

原文:https://www.cnblogs.com/minyDong/p/12465458.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!