我有一个 React 组件,它使用 querySelectorAll 来获取页面上元素的值,然后将它们呈现在组件中。使用下面的代码,我收到错误“无法将“label1”的属性设置为未定义”,但我不确定为什么,因为它使用 querySelector 正确查找值,并且 this.label1 是一个全局变量。
import React from 'react'
class StickyNav extends React.Component {
setLabels (labels) {
const [ label1, label2 ] = labels
if (!label1 || !label2) return
this.label1 = label1.textContent
this.label2 = label2.textContent
}
getQuery (query, callback) {
const el = document.querySelectorAll(query)
if (!el) return
if (callback) callback(el)
}
shouldComponentUpdate (nextProps, nextState) {
if (this.state.fixed !== nextState.fixed) {
this.getQuery('#navBar .form-group label', this.setLabels)
return true
}
return false
}
render () {
return (
<div>
<div className='form-group'>
<label htmlFor='choice1'><h4>{this.label1}:</h4></label>
<span id='choice1'> text</span>
</div>
<div className='form-group'>
<label htmlFor='choice2'><h4>{this.label2}:</h4></label>
<span id='choice2'> text</span>
</div>
</div>
)
}
}
export default StickyNav
最佳答案
您在此处引用此
:
setLabels (labels) {
const [ label1, label2 ] = labels
if (!label1 || !label2) return
this.label1 = label1.textContent
this.label2 = label2.textContent
}
但是 this
没有引用该实例。您必须在构造函数中绑定(bind)该方法或使用 ES7 类属性:
constructor(props) {
super(props)
this.setLabels = this.setLabels.bind(this)
}
或
setLabels = () => {....}
关于javascript - React - 无法设置未定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57003665/