文章目录
组件
- 无状态组件(函数式组件)
无state属性
function Hello(props) {
return <div>{props.name}</div>
}
ReactDOM.render(<Hello name='zs'/>,
document.getElementById('root'));
- 有状态组件(类组件)
有state属性
class Hello extends React.Component {
constructor(props) {
super(props); // 这里用了props,之后就可以直接用props.name就行,不需要this
}
render() {
return <div></div>
}
}
ReactDOM.render(<Hello name='zs'/>,
document.getElementById('root'));
react中的如何定义函数
- 箭头函数最常用的方法
class Hello extends React.Component {
updateInfo = () => {
console.log(this)
}
render() {
return <button onClick={this.updateInfo}>更新信息</button>
}
}
- 通过绑定this
class Hello extends React.Component {
constructor() {
this.updateInfo = this.updateInfo.bind(this); //方法二:在构造函数中绑定this
}
function updateInfo() {
console.log(this)
}
render() {//方法一:通过在触发的时候绑定this
return <button onClick={this.updateInfo.bind(this)}>更新信息</button>
}
}
函数中定义产生的问题,主要是有this引起的,在react中,开启局部严格模式,函数中的this指向undefined,而在constructor和render中this是指向该组件的,所以绑定this,可以实现功能