1.定义组件
//方法一:类似于构造函数的方式
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
//方法二:ES6中类的方式
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
ReactDOM.render(
<Welcome name="Tom"/>,
document.getElementById("app")
)
2.组件渲染
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const element = <Welcome name="Tom" />;
ReactDOM.render(
element,
document.getElementById('app')
);
——————————————————————————————————————————————————————————————————————————————————————————
分析过程:
1.我们对<Welcome name="Tom" />元素调用了ReactDOM.render()方法。
2.React将{name: 'Tom'}作为props传入并调用Welcome组件。
3.Welcome组件将<h1>Hello, Tom</h1>元素作为结果返回。
4.React DOM将DOM更新为<h1>Hello, Tom</h1>。
3.组件注意
1、组件定义的名称需以大写开头,区分函数定义;
2、React元素在何种方法中,均需以return返回;
3、组件的返回只允许有一个根元素;
4、提取组件时需注意,尽量提取复用性多的组件,哪怕只是一个按钮,表单,表格等;
5、组件是真正隔离的,同一个组件不同引用不互相影响;
4.props(只读性)
无论是使用函数或者类来声明一个组件,它决不能修改它自己的props
5.state(状态)
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
——————————————————————————————————————————————————————————————————————————————————————————
注意:
1.在 render() 方法中使用 this.state.date 替代 this.props.date;
2.添加一个类构造函数来初始化状态 this.state;
3.在类构造函数中使用 props 永远调用基础构造函数;
4.每次state变更,就会重新渲染,但只是重渲染改变的部分;
5.如需更改state,需使用 this.setState({date:new Date()}),切不可直接更新;
6.constructor构造函数是this.state初始化唯一的地方;