react 组件&props
一、函数组件和类组件
1.函数组件
有效的react函数组件
,接受唯一的参数props
,并返回一个react元素,在本质上是一个JavaScript函数
function Welcome(props){
return <h2>Welcome, {props.name}</h2>
}
2.类组件
类组件是一个es6的class,class中使用的props
来自于它的父组件
class Welcome extends React.Component{
render() {
return (
<h2>Welcome, {this.props.name}</h2>
);
}
}
该类组件与1中的函数组件等效
3.渲染组件,将组件放入元素
function Welcome(props){
return <h2>Welcome, {props.name}</h2>
}
const ele = <Welcome name="zhang3"/>;
ReactDOM.render(
ele,
document.getElementById('react_test')
);
执行过程:
- 调用
ReactDOM.render()
函数,并传入<Welcome name="zhang3" />
作为参数。 - React 调用
Welcome
组件,并将{name: 'zhang3'}
作为 props 传入。 Welcome
组件将<h2>Hello, zhang3</h2>
元素作为返回值。- ReactDOM 将 DOM 高效地更新为
<h2>Hello, zhang3</h2>
。
4.组合组件
组件可以在return()
中引用其他组件,这使得组件的配合使用和层次更加灵活
//注意props的使用
//函数组件
function Welcome(props) {
return <h2>Welcome, {props.name}</h2>
}
function Page() {
return(
<div>
<Welcome name="zhang3" />
<Welcome name="li4" />
<Welcome name="wang5" />
</div>
);
}
ReactDOM.render(
<Page />,
document.getElementById('react_test')
);
//若<Welcome />组件是由es6的class创建的,则props的使用需添加this
class Welcome extends React.Component{
render() {
return (
<h2>Welcome, {this.props.name}</h2>
);
}
}
//其余部分完全同上...