组件是React的基石,所有的React应用程序都是基于组件的。
1.实现一个最基础的组件:
Profile.jsx:
import React from 'react';
class Profile extends React.Component {
//render是这个组件渲染的Vitrual DOM
render() {
return(
<div className="profile-component">
{/*this.props是传入的属性*/}
<h1>我的名字叫{this.props.name}</h1>
<h2>我今年{this.props.age}岁</h2>
</div>
)
};
};
export default Profile;
app.jsx:
import React from 'react';
import { render } from 'react-dom';
import Profile from './Profile.jsx';
const ele = document.createElement("div");
document.body.appendChild(ele);
//此时父组件app.jsx通过props向子组件传值
const props = {
name:'lyn',
age:24
};
render(<Profile {...props} />,ele);
运行结果:
2.通过props和state实现一个组件(添加一个点击功能)
Profile.jsx:
import React from 'react';
class Profile extends React.Component {
constructor(props){
super(props);
this.state = {
liked:0
};
this.likedCallback = this.likedCallback.bind(this);
}
likedCallback(){
let liked = this.state.liked;
liked ++;
this.setState({
liked
});
}
//render是这个组件渲染的Vitrual DOM
render() {
return(
<div className="profile-component">
{/*this.props是传入的属性*/}
<h1>我的名字叫{this.props.name}</h1>
<h2>我今年{this.props.age}岁</h2>
<button onClick={this.likedCallback}>click me</button>
<h2>you have click me:{this.state.liked}</h2>
</div>
)
};
};
export default Profile;
state是组件内部的属性。组件可以在constructor中通过this.setState直接定义它的值。当state值变化时,可以通过this.setState方法让组件再次调用render方法,来渲染新的UI。
3.组合组件
React是基于组件的,所以一个组件可能会包含多个其他组件。
Hobby.jsx:
import React from 'react'
class Hobby extends React.Component {
render() {
return <li>{this.props.hobby}</li>
}
}
export default Hobby;
Profile.jsx:
import React from 'react';
import Hobby from './Hobby.jsx';
class Profile extends React.Component {
constructor(props){
super(props);
this.state = {
liked:0,
hobbies:['running','coding']
};
this.likedCallback = this.likedCallback.bind(this);
}
likedCallback(){
let liked = this.state.liked;
liked ++;
this.setState({
liked
});
}
//render是这个组件渲染的Vitrual DOM
render() {
return(
<div className="profile-component">
{/*this.props是传入的属性*/}
<h1>我的名字叫{this.props.name}</h1>
<h2>我今年{this.props.age}岁</h2>
<button onClick={this.likedCallback}>click me</button>
<h2>you have click me:{this.state.liked}</h2>
<h2>my hobby:</h2>
<ul>
{this.state.hobbies.map((hobby,i) => <Hobby key={i} hobby={hobby} />)}
</ul>
</div>
)
};
};
export default Profile;
app.jsx:
import React from 'react';
import { render } from 'react-dom';
import Profile from './components/Profile.jsx';
const ele = document.createElement("div");
document.body.appendChild(ele);
const props = {
name:'lyn',
age:24
};
render(<Profile {...props} />,ele);
运行结果: