组件的三大核心属性
state
state类式组件示例
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app"></div>
<script src="https://unpkg.com/react@17/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js" crossorigin></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
class Timer extends React.Component {
// 初始化状态,这里的状态就是当前的秒数
constructor(props) {
super(props);
// state初始化,这里可以直接使用 = 初始化
this.state = {seconds: 0};
}
// 定义tick方法,用于给秒数+1
// 注意: 状态数据只能调用setState方法更新,不可以直接操作
// 3. 让自定义函数在构造器中初始化bind() 从而绑定this
tick() {
this.setState(state => ({
seconds: state.seconds + 1
}));
}
// 组件被挂载时,启用interval
componentDidMount() {
// 注意,这里的this对象是当前组件的实例
// 自定义方法中this对象为undefined,解决办法有:
// 1. 箭头函数
// this.interval = setInterval(() => this.tick(), 1000);
// 2. 强制绑定this: 通过函数对象的bind()
this.interval = setInterval(function () {
this.tick();
}.bind(this), 1000);
}
// 组件被移除时,停止interval
componentWillUnmount() {
clearInterval(this.interval);
}
render() {
return (
<div>
Seconds: {this.state.seconds}
</div>
);
}
}
ReactDOM.render(
<Timer/>,
document.getElementById('app')
);
</script>
</body>
</html>函数式组件示例(hooks)
props
props...批量传递props
...批量传递props对props进行限制
函数式组件使用props
propsrefs
refs字符串形式的ref (废弃)
ref (废弃)回调形式的ref
refcrateRef() 推荐
crateRef() 推荐构造器
最后更新于