使用函数式创建
import {render} from \'react-dom\';
function Hello(props){
return (<div>{props.name}</div>)
}
render(<Hello name=\'yf\' />,document.getElementById(\'root\'))
使用React.createClass方式创建
import React from \'react\';
import {render} from \'react-dom\';
const Hello = React.createClass({
getInitialState:function(){
return {text:this.props.initialValue || \'placeholder\'}
},
render:function(){
return (<div>
<input type=\'text\' value={this.state.text} />
</div>)
}
})
render(<Hello initialValue=\'aaa\' />,document.getElementById(\'root\'))
使用React.Component创建
为了更好的实现复用,React极力推荐使用React.Component创建组件来取代React.createClass方法创建。是以ES6的形式来创建react的组件的
import React from \'react\';
import {render} from \'react-dom\';
class Hello extends React.Component{
constructor(props){
super(props);
this.state ={
text:this.props.initalValue || \'placeholder\'
}
}
render(){
return (<div>
<input type=\'text\' value={this.state.text} />
</div>)
}
}
render(<Hello initalValue = \'aaa\' />,document.getElementById(\'root\'))
JSX语法
const Hello = ()=>{
return (<div>
<p>这是一个段落</p>
</div>)
}
而这种JSX语法最终会被转换为React.createClass的方式被调用
const Hello = React.createClass({
render(){
return (<div>
<p>这是一个段落</p>
</div>)
}
})
//向下和解(Top-Down Reconciliation)
//最终转换的形式为DOM element形式
const Hello = ()=>({
type:\'div\',
props:{
children:{
type:\'p\',
children:\'这是一个段落\'
}
}
})
const Hello = React.createClass({
type:\'div\',
props:{
children:{
type:\'p\',
children:\'这是一个段落\'
}
}
})
相关文档:
https://tylermcginnis.com/react-elements-vs-react-components/
https://reactjs.org/blog/2015/12/18/react-components-elements-and-instances.html
继续阅读与本文标签相同的文章
下一篇 :
需还款800万元!又一电商平台宣布暂停运营
-
语音顶会Interspeech 论文解读|Audio Tagging with Compact Feedforward Sequential Memory Network and Audio-to-Audio Ratio Based Data Augmentation
2026-05-18栏目: 教程
-
SIA-GateWay之API网关安装部署指南
2026-05-18栏目: 教程
-
MySQL灵魂100问,你能答出多少?
2026-05-18栏目: 教程
-
如何入门 MySQL
2026-05-18栏目: 教程
-
Zabbix + Cloud Alert 实践分享
2026-05-18栏目: 教程
