import React, { Component } from 'react';
import propTypes from 'prop-types';
class TestComponent extends React.Component {
static defaultProps = {
name: 'testing component',
count: 1
}
static propTypes = {
name: propTypes.string.isRequired
}
constructor() {
this.state = {
name: '',
count: 1
};
}
// 16.3 deprecated
componentWilMount() {
console.log('初始化阶段1');
}
static getDerivedStateFromProps(nextProps, preState) {
console.log('初始化阶段1')
}
componentDidMount() {
console.log('初始化阶段2');
}
componentWillUnmount() {
console.log('卸载阶段1');
}
// 16.3 deprecated
componentWillReceiveProps(nextProps) {
console.log('运行阶段1');
}
shouldComponentUpdate(newProps, newState) {
console.log('运行阶段2');
if (!newProps.name) {
return false;
}
}
// 16.3 deprecated
componentWillUpdate(nextProps, nextState) {
console.log('运行阶段3');
}
getSnapshotBeforeUpdate(preProps, preState) {
console.log('更新阶段')
}
componentDidUpdate(preProps, preState) {
console.log('运行阶段4');
}
handleClick() {
console.log('react click 事件处理');
}
render() {
console.log('组件渲染了');
return (
<section id="demo">
<h1>
Hello {this.props.name}
</h1>
<p onClick={handleClick}>测试点击事件</p>
</section>
);
}
}
ReactDOM.render(
<TestComponent name="Taylor" />,
document.getElementById('root')
);
分三个阶段: 初始化(挂载)阶段、运行(更新)阶段、卸载阶段
class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
this.setState({value: event.target.value});
}
handleSubmit(event) {
alert('提交的名字: ' + this.state.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
名字:
<input type="text" value={this.state.value} onChange={this.handleChange} />
</label>
<input type="submit" value="提交" />
</form>
);
}
}
class NameForm extends React.Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.input = React.createRef();
}
handleSubmit(event) {
alert('A name was submitted: ' + this.input.current.value);
event.preventDefault();
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>
Name:
<input type="text" ref={this.input} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}