如何通过在 ReactJS 的回调中使用箭头函数来避免绑定?
在 React 基于类的组件中,当我们使用事件处理程序回调时,特别注意 'this' 关键字非常重要。在这些情况下,当回调函数实际被调用时,上下文 this 是未定义的,这就是我们必须绑定 this 的上下文的原因。现在如果绑定每个类的所有方法是很烦人的。我们可以使用内联箭头函数代替绑定,因为箭头函数没有自己的 this 值,它使用父值或公共值。使用内联箭头函数,我们可以摆脱烦人的方法绑定,而且代码看起来非常紧凑和有条理。
示例 1:此示例说明如何在回调中使用箭头函数
index.js:
Javascript
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render( , document.querySelector('#root'))
Javascript
import React, { Component } from 'react'
class App extends Component {
// Default props
static defaultProps = {
courseContent : [
'JSX', 'React Props', 'React State', 'React Lifecycle Methods',
'React Event Handlers', 'React Router', 'React Hooks', 'Readux',
'React Context'
]
}
constructor(props){
super(props)
// Set initial state
this.state = {msg : 'React Course', content:''}
}
// Return an unordered list of contents
renderContent(){
return (
{/* map over all the contents and
return some JSX for each */}
{this.props.courseContent.map(content => (
- {content}
))}
)
}
render(){
const button = !this.state.content &&
return (
{this.state.msg}
{this.state.content}
{button}
)
}
}
export default App
Javascript
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render( , document.querySelector('#root'))
Javascript
import React, { Component } from 'react'
class App extends Component{
// Default props
static defaultProps = {
name : ['John', 'Alex', 'Bob']
}
constructor(props){
super(props)
// Nnitialize count state
this.state = {msg : 'Hi There', count:0}
}
render(){
return(
Greetings!
{this.state.msg}
)
}
}
export default App
应用程序.js:
Javascript
import React, { Component } from 'react'
class App extends Component {
// Default props
static defaultProps = {
courseContent : [
'JSX', 'React Props', 'React State', 'React Lifecycle Methods',
'React Event Handlers', 'React Router', 'React Hooks', 'Readux',
'React Context'
]
}
constructor(props){
super(props)
// Set initial state
this.state = {msg : 'React Course', content:''}
}
// Return an unordered list of contents
renderContent(){
return (
{/* map over all the contents and
return some JSX for each */}
{this.props.courseContent.map(content => (
- {content}
))}
)
}
render(){
const button = !this.state.content &&
return (
{this.state.msg}
{this.state.content}
{button}
)
}
}
export default App
输出 :
示例 2:
index.js:
Javascript
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render( , document.querySelector('#root'))
应用程序.js:
Javascript
import React, { Component } from 'react'
class App extends Component{
// Default props
static defaultProps = {
name : ['John', 'Alex', 'Bob']
}
constructor(props){
super(props)
// Nnitialize count state
this.state = {msg : 'Hi There', count:0}
}
render(){
return(
Greetings!
{this.state.msg}
)
}
}
export default App
输出 :