私はReact.jsを初めて使用し、イベントハンドラーを機能させることができないようです。匿名の内部クラスとしてではなく、render関数の外部でイベントハンドラーを作成すると、上記のエラーが発生します。誰かが私が間違っていることを指摘できますか?
class Checkboxes extends Component{
constructor(props) {
super(props);
this.state = { checked: [true, true],
frame: [values, values],
title: ['A', 'B'] };
this.handleChange= this.handleChange.bind(this);
}
handleChange(e) {
let index= e.target.id;
let newState = this.state.checked.slice();
newState[index] = !this.state.checked[index];
this.setState ({checked: newState});
}
render(){
const selectionBoxes = this.state.title.map(function(title, index) {
return (
<div className="w3-checkbox" id={index} onClick={this.handleChange}>
<input
type="checkbox"
label={'Division '+title}
value={this.state.checked[index]}
checked={!this.state.checked[index]}
onChange= {this.handleChange}
id={index} />
<label id={index} onClick={this.handleChange}>
{'Division '+ title}
</label>
</div>
);
});
const frameDisplay = this.state.frame.map(function(frame, index) {
return (
<div>
{this.state.checked[index]} ? null :
<DivFrame frameId={frame} width={this.state.width} height={this.state.height} title={this.state.title[index]} />
</div>
);
});
return (
{selectionBoxes}
);
}
};
export default Checkboxes;
コンストラクターでhandleChange
toをバインドしたthis
としても、それはまだthis.state.title.map(function(title, index) {...
関数内のスコープ内にないようです。に変更this.state.title.map(function(title, index) {...
するだけでこの問題を修正しましたthis.state.title.map((title, index) => {...
これはES6構文であり、バインディングを自動的に実行します。
デモについてはこちらをご覧ください:https://codesandbox.io/s/py2zp8z1kj
簡単にするために、framesコンポーネントに関連するコードは実際には問題に関連していないため削除し、そのコンポーネントを実装するために必要な作業を削減することに注意してください。イベントハンドラーをそのコンポーネントでも機能させるには、マッピング関数のコールバックもES6構文に変更する必要があります。
また、あなたがでていることがわかりますreturn
のrender()
ため、あなたがそれらを必要としないための方法、私は中括弧を削除したselectionBoxes
評価されるべきではない生のHTMLやニーズがあります。実際にそれを評価する({ selectionBoxes}
)は、の値をselectionBoxes
有効な反応子ではないオブジェクトに変換します。したがってselectionBoxes
、レンダリングブロックにそのまま配置します。
デモを表示できない場合、コードは次のようになります。
class Checkboxes extends Component {
constructor(props) {
super(props);
this.state = {
checked: [true, true],
frame: [0, 1],
title: ['A', 'B']
};
}
handleChange(e) {
let index = e.target.id;
let newState = this.state.checked.slice();
newState[index] = !this.state.checked[index];
this.setState({ checked: newState });
}
render() {
const selectionBoxes = this.state.title.map( (title, index) => {
return (
<div className="w3-checkbox" id={index} onClick={this.handleChange}>
<input
type="checkbox"
label={'Division ' + title}
value={this.state.checked[index]}
checked={!this.state.checked[index]}
onChange={this.handleChange}
id={index} />
<label id={index} onClick={this.handleChange}>
{'Division ' + title}
</label>
</div>
);
});
return (
selectionBoxes
);
}
};
export default Checkboxes;
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加