react怎么构建组件

首先是

ES5的写法:
const Com1 = React.createClass({
//创建一个类,就是构建一个组件 
  render(){
    return 

hello ES5 react component!!!

} }); ReactDOM.render(

Hello React!!!

, document.querySelector(".box") )
ES6 写法
class Com2 extends React.Component{
    render(){
        return  

Hello ES6 React component

} }; ReactDOM.render(

Hello React!!!

{/*单双标签都可以,只要有结束字符就可以 可以写成*/}
, document.querySelector(".box") )

我们在class Com2 里面写一个根节点

class Com2 extends React.Component{
    constructor(props){
        super(props);
    }
    render(){
        return 

Hello ES6 React component

{ this.props.msg }

{/**/}
} }; ReactDOM.render(

Hello React!!!

, document.querySelector(".box") )

在标签上传值

我们在 Com2 标签上进行传值,我们通过标签属性设置了一个msg,我们怎么拿到 msg 呢,就是 在class 里面,写一个标签把变量放在标签里面{ this.props.msg }
但是,ES6 继承下来的类,没有this,要显示的传,一个constructor(props){
super(props);}

const Com1 = React.createClass({
    getDefaultProps(){
        return {
            msg :"默认的msg"
        }
    },
    propTypes:{
        msg : React.PropTypes.oneOf(["a","b"])
    },
    render(){
        console.log(1,this.props)
        console.log(2,this.props.children)
        return 

Hello React component ES5

{ this.props.msg }
    { this.props.items.map((item,i)=>{ return
  • { item }
  • }) }
{this.props.children} {/* this.props.children.map((m,n)=>{ return { m } })*/ } { React.Children.map(this.props.children,(m,n)=>{ return {m} }) }
} }); ReactDOM.render(

Hello React!!!

, document.querySelector(".box") )

this.props

组件外向组建内传值,用this,props
传值的方法是一样的,在标签里面写一个属性,但是接值得时候方法不一样:由于继承的子类没有this(作用域),所以在ES6中,需要使用construtor 得到 this
// 而在ES5中,createClass 所创建的类,自动拥有this,可直接使用this.props
// this.props 得到父集向下传递的数据
// this.props.children 得到组件的原始内容(子元素)
//当有一个子元素时,返回对象
// 当有多个元素时,返回数组
// 没有子元素时,返回 undefined

一个组件,两个地方用,
把组件一,items 的t1,t2.t3.用this.props.items.map()的方法遍历出来,用 li 标签包裹
我们再在组件里面添一个属性,

你可能感兴趣的:(react怎么构建组件)