react组件
react组件主要有两种形式,一种是class组件,一种是函数组件,class组件扩展性强,写起来较为繁琐。函数组件功能单一,但写起来简单。
class组件
class List extends React.Component {
render() {
return (
<button className="square" onClick={function() { alert('click'); }}> {this.props.value}
</button>
);
}
}
函数组件
function List(props) {
return (
<button className="list" onClick={props.onClick}>
{props.value}
</button>
);
}
生命周期
componentDidMount---挂载,componentWillUnmount---卸载,下述示例为组件挂载时设置一个定时器,组件卸载时清除掉定时器。
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
// 组件挂载
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
// 组件卸载
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
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')
);
state
state用来维护组件内部的数据状态。类似于vue2中的data。改变state时通过setState方法来改变。
class ZButton extends React.Component {
constructor(props) {
super(props);
this.state = {
value: null,
};
}
render() {
return (
<button
className="btn"
onClick={() => this.setState({value: 'X'})}
>
{this.state.value}
</button>
);
}
}
重要思想
状态提升
通常,多个组件需要反映相同的变化数据,这时建议将共享状态提升到最近的共同父组件中去。
单向数据流
数据自上而下传递。
不可变性
功能逻辑复杂时,复制一份数据出来操作,尽量不要操作源数据,保持源数据不被改变。
浙公网安备 33010602011771号