我正在制作非常简单的 react 应用程序。然而,当我尝试通过 onChange 事件调用父(实际上是祖 parent )组件的方法时,我不断收到 Uncaught TypeError: Cannot read property 'props' of undefined
。
这是触发事件的组件/表单(从而调用绑定(bind)父组件上的方法...是的,当我通过 props 从父组件传递它时,我在方法上使用了 .bound(this) 。)。
class MonthsTable extends Component {
handleChangeOnMonth(e){
this.props.setMonth(e.target.id, e.target.value); // here the method is not found, causing error.
}
render(){
console.log(this.props.setMonth) // here the method is present alright
return (<form>
{this.props.months.map((e, i) =>
<input
type='number'
id={i}
key={i} // yes I know, bad habit, but in this case it doesn't matter
value={this.props.months[i]}
onChange={this.handleChangeOnMonth} />)}
</form>)
}
}
以下是我如何将方法作为大多数父(祖 parent )组件的 props 传递。
<Months setMonth={this.setMonth.bind(this)} />
以下是我如何将方法作为父级(方法所有者和方法调用者之间的组件)中的 props 传递
<MonthsTable setMonth={this.props.setMonth} />
最后传递给您首先看到的组件(MonthsTable)。无论是否相关,最终(大多数子)组件的显示取决于 if 语句,它工作得很好(可能以某种方式相关,我不知道)。
问题是...为什么 (setMonth) 方法在 (handleChangeOnMonth) 方法内部“不可见”。
最佳答案
这里的实际问题是 this
上下文没有在 handleChangeOnMonth
函数中定义。这是由于 javascript 处理函数上下文的方式引起的,基本上在调用函数时,如果您不直接从对象调用它们,并且它们没有绑定(bind),它们将没有定义的上下文,并且由于您传递的是函数作为输入组件的参数,它会丢失上下文。
解决这个问题最简单的方法是绑定(bind)函数,我建议你在构造函数中绑定(bind)函数,如下所示:
class MonthsTable extends Component {
constructor(props, context){
super(props, context);
this.handleChangeOnMonth = this.handleChangeOnMonth.bind(this);
}
handleChangeOnMonth(e){
this.props.setMonth(e.target.id, e.target.value);
}
render(){
return (<form>
{this.props.months.map((e, i) =>
<input
type='number'
id={i}
key={i}
value={this.props.months[i]}
onChange={this.handleChangeOnMonth} />)}
</form>)
}
}
或者,如果您使用装饰器,则可以使用 core-decorators
包以更优雅的方式执行此操作:
import {autobind} from "core-decorators"
@autobind
class MonthsTable extends Component {
handleChangeOnMonth(e){
this.props.setMonth(e.target.id, e.target.value);
}
render(){
return (<form>
{this.props.months.map((e, i) =>
<input
type='number'
id={i}
key={i}
value={this.props.months[i]}
onChange={this.handleChangeOnMonth} />)}
</form>)
}
}
关于javascript - React.js - 无法读取未定义的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39176248/