您好,欢迎来到二三四教育网。
搜索
您的当前位置:首页react怎么构建组件

react怎么构建组件

来源:二三四教育网

首先是

ES5的写法:
const Com1 = React.createClass({
//创建一个类,就是构建一个组件 
  render(){
    return <h1>hello ES5 react component!!!</h1>
  }
});
ReactDOM.render(
    <div>
        <h1>Hello React!!!</h1>
        <Com1></Com1>
    </div>,
    document.querySelector(".box")
)
ES6 写法
class Com2 extends 
    render(){
        return  <h1>Hello ES6 React component</h1>
    }
};
ReactDOM.render(
    <div>
        <h1>Hello React!!!</h1>
        <Com1></Com1>
              {/*单双标签都可以,只要有结束字符就可以  <Com2></Com2>可以写成<Com2/>*/}
                <Com2></Com2>
    </div>,
    document.querySelector(".box")
)

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

class Com2 extends 
    constructor(props){
        super(props);
    }
    render(){
        return <div>
<h1>Hello ES6 React component</h1>
<h3>{ this.props.msg }</h3>
{/*<Com1 msg="随便" items={["t4","t5","t6"]}></Com1>*/}
            </div>
            
    }
};
ReactDOM.render(
    <div>
        <h1>Hello React!!!</h1>
<Com1 msg="你好"/>
        <Com2 msg="你好" ></Com2>
    </div>,
    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 <div>
            <h1>Hello React component ES5</h1>
            <span>{ this.props.msg }</span>
            <ul>
                {
                    this.props.items.map((item,i)=>{
                        return <li key={ i }>{ item }</li>
                    })
                }
            </ul>
            {this.props.children}
            {/*
                this.props.children.map((m,n)=>{
                    return <i key={n}>{ m }</i>
                })*/
            }
            {
                React.Children.map(this.props.children,(m,n)=>{
                    return <b key={n}>{m}</b>
                })
            }
        </div>
    }
});
ReactDOM.render(
    <div>
        <h1>Hello React!!!</h1>
        <Com1 msg="b" 
        items={ ["t1","t2","t3"] }>
        </Com1>

        <Com2 msgs="你好" ></Com2>
        <Com2 />
    </div>,
    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 标签包裹
我们再在组件里面添一个属性,

Copyright © 2019- how234.cn 版权所有 赣ICP备2023008801号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务