首页 > 其他 > 详细

react组件的应用

时间:2020-08-31 20:54:44      阅读:47      评论:0      收藏:0      [点我收藏+]

react中定义组件的两种方式:

方式一:函数式组件

const 组件名(首字母大写) = (props) =>{
			reture (
				jsx表达式
			)
		}
const App = ()=>{
	return (
		<div>
			<h2>我是h2</h2>
		</div>
	)
}
//或者另一种写法
function App(){
	return (
		<div>
			<h2>我是h2</h2>
		</div>
	)
}


//调用组件
reactDOM.render(</App>,document.getElementById("app"))//开始渲染真实dom

如果想要在组件里面插入参数

const App = ()=>{
	return (
		<div>
			{props.children}
			<h2>我是h2</h2>
		</div>
	)
}

reactDOM.render(<App><p>我是新插入的哦</p></App>,document.getElementById("app"))

就会在组件h2上面显示“我是新插入的哦”这行文字。

还可以分开插入好几个数据,在组件中应该以数组的形式显示,所以应该用下标控制选择。

const App = ()=>{
	return (
		<div>
			{props.children[1]}//显示h4标签内容
			<h2>我是h2</h2>
			{props.children[0]}//显示p标签内容
		</div>
	)
}

reactDOM.render(<App><p>我是新插入的哦</p><h4>我是h4标签哦</h4></App>,document.getElementById("app"))

方式二:类组件

书写模式:必须要有render钩子函数和return

class 组件名  extends  React.Component {
	render(){ //render是必不可少的钩子函数
		return jsx表达式
	}
}

这里如果往组件插入数据的话,与函数式组件有些不同,格式为this.props.children。下面举个案例

class App extends React.Component{
            render(){  //必写的钩子函数
                return (
                    <div>
                        <h2>我是h2标签哦...</h2>   
                        <div>
                            {this.props.children}    
                        </div>
                    </div>
                )
            }
        }
        

ReactDOM.render(<App><p>我是新插入的哦</p><h4>我是h4标签哦</h4></App>,document.getElementById("app"))

两种组件的对比

函数式组件中没有this,为空,类组件中有this

类组件中:

? 通过this.props.xxx获取外部传入的属性值

? 函数式组件中:

? 通过参数props.xxx获取外部传入的属性值

<div id="app"></app>

const App = function(props){
	return(
		<div>
           我是app组件! --- { props.username }
        </div>
	)
}

let obj = {
       sex:"女"
     }

ReactDOM.render(<App username={"张三"} sex={obj.sex}/>,document.getElementById("app"))

react中表达式对于对象的处理

在react里我们不能直接渲染对象, 需要想办法先转化成数组,object.keys(obj)===>此时就返回了一个数组,想取值的话,需要用到[]取值,具体如下例题

let obj = {a:1,b:2}  //["a","b"]
        class App extends React.Component{
            render(){
                return (
                    <div>
                        {
                        //Object.keys(obj)会获取到数组的形式。
                            Object.keys(obj).map((item,index)=>{
                                return <p key={index}>{item} : {obj[item]}</p>
                            })
                        }
                    </div>
                )
            }
        }
        
        ReactDOM.render(<App/>,document.getElementById("app"))

react组件的应用

原文:https://www.cnblogs.com/axingya/p/13591274.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!