reactJS -- 7 可复用组件(Prop 验证)

React子组件传值与属性验证
本文介绍React中如何实现子组件间的数据传递及属性验证。通过实例演示了如何设置propTypes来确保父组件向子组件正确传递所需类型的数据,并展示了如何使用defaultProps设置默认属性值。

一.参考文档

为了防止传入参数类型错误,增加参数验证。

http://www.react-cn.com/docs/reusable-components.html

二. 给类定义属性

BodyIndex.propTypes = {
  userId : React.PropTypes.number.isRequired ; //必须传入参数
  userId : React.PropTypes.number; // userId被规定为数值型
}

BodyIndex.defaultProps = defaultProps; //设置默认值,没有参数传进来时自己也存在默认值

三.代码

必须向子页面传入userId

import React from 'react';
import ReactDOM from 'react-dom';
//引入body子页面
import BodyChild from './BodyChild'

const defaultProps = {
  userName : "这是一个默认的 userName"
}
//export 暴露
export default class BodyIndex extends React.Component {
  constructor(){   //类的构造函数
    super(); // 调用基类的所有的初始化方法
    this.state = {
      userName: "parray",
      age: 10
    }; //初始化赋值
  }

  //创建事件
  changerUserInfo(age) {
    this.setState({age : age});
  }

  /**
   * 创建 input 改变事件
   * @param  {Event} event [description]
   * @return {[type]}       [description]
   */
  handleChildValueChange(event){
    this.setState({
      age : event.target.value
    })
    return '';
  }
  render() {   //解析类的输出

    return (
      <div>
        <div className="c" id="id">alex asd content</div>
        <h2>页面主体内容</h2>
        <p>接收到的父页面的属性 :userId: {this.props.userId} userName : { this.props.userName}</p>
        <p>age:{this.state.age}</p>
        <input type= "button" value="submit" onClick={this.changerUserInfo.bind(this, 99)}/>
        <BodyChild { ...this.props}  id={4} handleChildValueChange = {this.handleChildValueChange.bind(this)}/>
      </div>
    )
  }
}

BodyIndex.propTypes = {
  userId : React.PropTypes.number.isRequired; //必须向子页面传入userId参数
}

BodyIndex.defaultProps = defaultProps; // 默认值

/* 在类定义完后可以追加属性
BodyIndex类有一个属性 :propTypes,传入参数
1.定义 父页面传入的userId Prop 验证
userId : React.propTypes.number; 类型的强制约束,只能是number类型值
2. 父页面中调用子页面,设置必须传入 属性 : .isRequired
3. 设置默认值 :defaultProps
4. 想把从父页面传进来的参数,直接传给他的子页面
{ ...this.props}--得到父页面从父级得到的所有值
有新添加了一个属性
*/

四.  得到父级页面从父级页面的父级得到的所有值

{ ...this.props}

  <BodyChild { ...this.props}  id={4} handleChildValueChange = 

{this.handleChildValueChange.bind(this)}/>

index.js(根页面)

var React = require('react');
var ReactDOM = require('react-dom');
import ComponentHeader from './components/header';  // (./)当前目录下
import ComponentFooter from './components/footer';
import BodyIndex from './components/bodyIndex'
class Index extends React.Component {
	componentWillMount(){
    //定义你的逻辑
    console.log("Index - componentWillMount")

  }
  componentDidMount(){
    console.log("Index - componentDidMount");
  }
	render() {
		//可以将组件定义为参数
		const component = (
			<ComponentHeader/>
		)
		return (
			<div>
				{component}  {/*利用参数形式调用*/}
				<BodyIndex userId = {123456}/>
				<ComponentFooter/>
			</div>
		);
	}
}
ReactDOM.render(
	<Index/>, document.getElementById('example')
);

bodychild.js

import React from 'React';

export default class BodyChild extends React.Component{

  render(){
    return(
      <div>
      {/* 当子页面input onchange 发生改变, 调用传入的handleChildValueChange 函数*/}
          <p>子页面输入: <input type= "text" onChange={this.props.handleChildValueChange}/> </p>
          <p> 父页面userId :{this.props.userId}  父页面userName :{ this.props.userName} 新增加的ID:{ this.props.id} </p>
      </div>
    )
  }
}

/* 在父页面中 声明事件
//创建 input 改变事件
  handleChildValueChange(event){
    this.setState({age : event.target.value})
  };

  通过 :event.target.value 获取input的值
*/

 

转载于:https://my.oschina.net/u/2991733/blog/1142775

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值