매우 간단한 반응 앱을 만들고 있습니다. 그러나 onChange 이벤트를 통해 parent (실제로 조부모) 컴포넌트의 메소드를 호출하려고 시도 할 때 나는 계속 Uncaught TypeError: Cannot read property 'props' of undefined
을 얻는다.React.js - 정의되지 않은 속성을 읽을 수 없습니다.
다음은 이벤트를 트리거하는 구성 요소/폼입니다 (따라서 바인딩 된 부모 구성 요소에서 메소드를 호출합니다 ...). 예. 부모 구성 요소에서 소품을 통해 전달할 때 메소드에서 .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>)
}
}
다음은 대부분의 부모 (조부모) 구성 요소의 소품으로 메서드를 전달하는 방법입니다. 여기
<Months setMonth={this.setMonth.bind(this)} />
내가 부모에
<MonthsTable setMonth={this.props.setMonth} />
그리고 마지막 구성 요소를 처음 보았다 (MonthsTable)에 전달 (방법 소유자 및 방법 호출자 사이에 구성 요소를) 소품 등의 방법을 전달하는 방법이다 . Wheter 관련성 여부와 관계없이 최종 (대부분의 자식) 구성 요소는 잘 작동하는 if 문에 따라 표시됩니다 (어쨌든 관련성이 있을지 모르지만).
질문 : 왜 (setMonth) 메서드가 (handleChangeOnMonth) 메서드 내부에서 '보이지 않음'입니까?
어떤 조언을 주셔서 감사합니다.
'this.handleChangeOnMonth'을 (를)'this '에 바인딩 해보세요. –