组件内属性
- props
- state
定义组件
react中官方推荐尽可能使用无状态组件定义,如果涉及state,生命周期使用component方式创建组件
1. 定义无状态组件
利用箭头函数就可以定义
const HelloMessage = (props) => <div> Hello {props.name}</div>;
render(<HelloMessage name="John" />, mountNode);
2. 利用extends Component创建组件类
import React, { Component } from 'react';
import { render } from 'react-dom';
class LikeButton extends Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
handleClick(e) {
this.setState({ liked: !this.state.liked });
}
render() {
const text = this.state.liked ? 'like' : 'haven\'t liked';
return (
<p onClick={this.handleClick.bind(this)}>
You {text} this. Click to toggle.
</p>
);
}
}
render(
<LikeButton />,
document.getElementById('example')
);
参考: