react里面有两种创建组件的方法,函数式创建组件便是其中一种
特点:1.创建函数式组件结果会返回一个新的jsx元素(也就是当组件的jsx结构)
- 函数式组件的props参数存储的值是一个对象,包含了调取组件时传递的属性值(如果不传则为一个空对象)
示例:
创建函数式组件
//用到jsx就必须导入react
import React from 'react'
export default function FormalDialog(props) {
// 解构赋值拿到需要的数据
let {title, children} = props
console.log(props)
return <section className="box">
<div className="header">
{/* 判断text属性是否有值,有则显示,无则显示默认文字 */}
{title.text ? title.text : '提示'}
{/* 判断type属性值是否为‘success’,有则显示,无则显示默认文字 */}
{title.type === 'success' ? '成功' : null}
</div>
<div className="content">
{/* 判断children属性是否有值,有则显示,无则显示默认文字 */}
{children ? children : '这是我的第一个react组件'}
</div>
<div className="footer">
<button>确定</button>
<button>删除</button>
</div>
</section>
}
调用函数式组件
import React from 'react';
import ReactDOM from 'react-dom';
// 调用函数式组件
import Dialog from './component/Dialog.js'
ReactDOM.render(<div>
{/*创建标签属性值title,如果值不为字符串要使用jsx语法用{}包起来*/}
<FormalDialog title={{text: "😀", type: 'success'}}>
{/*传递children值(可以为子标签,字符。)*/}
<h4>哈哈哈</h4>
<h4>嘻嘻嘻</h4>
</FormalDialog>
</div>, document.getElementById("root"))
注意:在调用createElement方法执行当中(例如:
createELement(<Dialog/>)
),遇到一个组件,返回的对象当中type不再是一个字符串(标签名),而是一个函数一个类,但属性还是存在于props中。
网友评论