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> 2 <html> 3 <head> 4 <meta http-equiv='Content-type' content='text/html; charset=utf-8'> 5 <title>daomul's example</title> 6 <link href="https://www.jb51.net/shared/css/base.css" /> 7 </head> 8 <body> 9 <h1>Text demo</h1> <div> </div> <script src="https://www.jb51.net/shared/thirdparty/es5-shim.min.js"></script> <script src="https://www.jb51.net/shared/thirdparty/es5-sham.min.js"></script> <script src="https://www.jb51.net/shared/thirdparty/console-polyfill.js"></script> <script src=""></script> <script src=""></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 属性和状态的一些总结就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章: