函数式组件
直接以函数的方式声明,并且返回的组件内容(JSX
语法)]
以下代码拷贝可直接运行:
<body>
<div id="app"></div>
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
function Hello({ msg }) {
return <h1>Hello,{msg}</h1>
}
ReactDOM.render(<Hello msg={'函数式组件'} />, document.querySelector('#app'))
</script>
</body>
props
的接收可以使用解构赋值
类组件
运用ES6
的class
语法实现,不熟悉的同学可以去看看文档。要继承React.Component
类!!
以下代码拷贝可直接运行:
<body>
<div id="todo"></div>
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
class TodoList extends React.Component {
render() {
return (
<ul>
{
this.props.data.map(item => <li key={item.id}>{item.name}</li>)
}
</ul>
)
}
}
const data = [{ id: 1, name: 'Vue' }, { id: 2, name: 'React' }, { id: 3, name: 'NuxtJS' }]
ReactDOM.render(<TodoList data={data} />, document.querySelector('#todo'))
</script>
</body>
运行结果将会是一个列表。注意:JSX
语法中大括号里只可以写表达式