欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

浅谈React 属性和状态的一些总结

程序员文章站 2022-03-14 09:21:37
...
一、属性

1、第一种使用方法:键值对

<ClaaNameA name = “Tom” />

<ClaaNameA name = {Tom} />

<ClaaNameA name = {“Tom”} />

<ClaaNameA name = {[1,2,3]} />//数组

<ClaaNameA name = {FunctionNAme} /> //定义一个函数

2、第二种方法:三个点的展开对象形式

var props = {
 
one :”123”,
 
tow :321
 
 }
 
<ClassNameB {…props} />

增加三个引号相当于这里面拿到两个属性了(one和two)

3、setProps形式:通过组件更新属性,不能在组件内部中修改属性的,因为会违背组件设计原则(尽量避免)

var instance =React.render(<ClassNameC ><ClaasNameC/>,document.body);
 
instance.setProps({name:”Tom" });

二、状态:事物所处的状况,由事物自行处理不断变化/事物的私有属性

getInitialState:初始化每个实例特有的状态

setState:更新组件状态

setState会触发diff算法:判断state和页面结果的区别,是否需要更新

三、状态和属性对比

状态和属性都会触发render更新,都是纯JS对象

状态:是和自己相关的,既不受父组件也不受子组件影响

属性:本身是不能自己去修改的,只能从父组件获取属性,父组件也能修改它的属性

根本的区别:组件在运行时需要去修改维护的就是状态

四、简单的demo熟悉一下:

<!DOCTYPE html>
 <html>
  <head>
   <meta http-equiv='Content-type' content='text/html; charset=utf-8'>
   <title>daomul's example</title>
   <link rel="stylesheet" href="../shared/css/base.css" />
  </head>
  <body>
   <h1>Text demo</h1>
  <div id="container">
 
  </div>
 
  <script src="../shared/thirdparty/es5-shim.min.js"></script>
  <script src="../shared/thirdparty/es5-sham.min.js"></script>
  <script src="../shared/thirdparty/console-polyfill.js"></script>
  <script src="../../build/react.js"></script>
  <script src="../../build/JSXTransformer.js"></script>
  <script type="text/jsx">
 
    //内容组件
    var Content = React.createClass({
     getInitialState:function(){
      return {
       inputText:'',
      };
     },
     handleChange:function(event){
      this.setState({inputText:event.target.value});
     },
     handleClick:function(){
      console.log("props name is " + this.props.selectName + " \n and inputText is " + this.state.inputText);
     },
     render:function(){
 
      return <div>
       <textarea onChange = {this.handleChange} placeholder = "please input something!"></textarea>
       <button onClick = {this.handleClick}>sumbit</button>
      </div>;
     },
    });
 
    //评论组件
    var Comment = React.createClass({
     getInitialState:function(){
      return {
       names:["Tom","Axiba","daomul"],
       selectName:'',
      };
     },
     handleSelect:function(){
      this.setState(
        {selectName : event.target.value}
       );
     },
     render:function(){
      var options = [];
      //往options中添加子option
      for (var option in this.state.names) {
       options.push(<option value={this.state.names[option]}> {this.state.names[option]} </option>)
      };
      return <div>
       <Content selectName = {this.state.selectName}>
       </Content>
       <select onChange = {this.handleSelect}>
        {options}
       </select>
      </div>;
     },
    });
 
    //start render
    React.render(<Comment></Comment>,document.body);
  </script>
 </body>
</html>
相关标签: React