import React from 'react'
import ReactDOM from 'react-dom'
function tick() {
let ele = <h1>{
new Date().toLocaleTimeString() }</h1>
// Objects are not valid as a React child (found: Sun Aug 04 2019 20:34:51 GMT+0800 (中国标准时间)). If you meant to render a collection of children, use an array instead.
// new Date() 是一个对象数据类型的值,React 元素不接收对象作为其子元素
ReactDOM.render(ele, document.querySelector('#root'))
}
tick()
setInterval(tick, 1000) // 如果不包在一个函数中,时钟是不会每秒更新一次
但是 React 和 Vue 相同都是数据驱动的,但是这个时候和数据驱动没啥关系,每隔1秒钟重新创建一个 ele,然后再渲染到页面中,视图才发生变化;为了使用数据驱动,我们需要使用 React 的组件
在 React 组件中,jsx 元素(也称 react 元素)是组件的基本组成单位
在 react 中定义组件有两种方式:
react 使用函数定义组件,就是声明一个函数;
// 1. 函数定义组件
function Welcome(props) {
// props 是一个对象,是使用组件时,写在组件行内的属性和属性值组成的;
console.log(data)
return (<div>
<p>{
props.data.name}; {
props.data.age}</p>
<p>{
props.x}</p>
</div>)
}
ReactDOM.render(<Welcome data={
{
name: 'mabin', age: 18}} x='hahah' />, document.querySelector('#root'));
通过 class 定义一个组件
-看🌰
class Header extends Component {
constructor () {
super()
}
render () {
// 在 render 函数中通过 this.props 访问 props
return (<div>
{
this.props.content}
</div>)
}
}
class Hello extends Component {
constructor (props) {
super()
// 注意在构造函数中不能访问 this.props ,props 会作为形参传入
}
render () {