React Native组件、生命周期及属性传值props详解
创建组件的三种方式第一种:通过ES6的方式创建 /** * 方式一 :ES6 */ export default class HelloComponent extends Component { render (){ return <Text style={{fontSize:20,backgroundColor:‘red‘}}>Hello</Text> } } ? ? 第二种:通过ES5的方式创建 /** * 方式二:ES5 */ var HelloComponent= React.createClass( { render (){ return <Text style={{fontSize:50,backgroundColor:‘red‘,marginTop:200}}>Hello:{this.props.name}</Text> } } ); module.exports = HelloComponent; ? 第三种:函数式定义 /** * 方式三:函数定义 * 无状态,不能使用this */ function HelloComponent(props){ return <Text style={{fontSize:20,backgroundColor:‘red‘}}>Hello</Text> } module.exports = HelloComponent; ? ? 组件的生命周期在React 中组件(Component)也是有自己的生命周期方法的。展示一个界面从创建到销毁的一生。? 组件的生命周期分成三个状态:? Mounting:已插入真实 DOM? shouldComponentUpdate(object nextProps,object nextState): 在接收到新的 props 或者 state,将要渲染之前调用。? 心得:可以根据实际情况来重写次这些生命周期的方法,灵活的控制组件当 props 和 state 发生变化时是否要重新渲染组件。? 注意:你不能在该方法中使用 this.setState()。如果需要更新 state 来响应某个 prop 的改变,请使用 componentWillReceiveProps。? 3 Unmounting(移除)? 组件详解使用前两种方法创建组件的时,必须提供render方法.? static DefaultProps={ name:‘小米‘,isRequire:true,} ? 注意,该方法在任何实例创建之前调用,因此不能依赖于 this.props。另外,getDefaultProps() 返回的任何复杂对象将会在实例间共享,而不是每个实例拥有一份拷贝。该方法在你封装一个自定义组件的时候经常用到,通常用于为组件初始化默认属性。? static PropTypes={
Image.PropTypes.source,leftButtonTitle: React.PropTypes.string,}
? #延展操作符 …? var prames = {mount:1,name:‘小米‘,age:12}; <HelloComponent {...prames} /> 在 HelloComponent中的代码为: constructor(props){ super(props); this.state={ mount:10,name:‘小红‘,age:10,} } render (){ return ( <View> <Text style={{fontSize:20,backgroundColor:‘red‘}}>Hello {this.state.name+‘ 你的年纪是:‘+this.state.age+‘ 成绩排名是:‘+this.state.mount}</Text> <Text style={{fontSize:20,backgroundColor:‘red‘}}>Hello {this.props.name+‘ 你的年纪是:‘+this.props.age+‘ 成绩排名是:‘+this.props.mount}</Text> </View> ) } 输出: Hello 小红 你的年纪是10 成绩排名是10 Hello 小米 你的年纪是12 成绩排名是1 注意:this.props.XXX与this.state.XXX (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |