リファレンスは、公式ドキュメント反応するイベントを
最初:矢印結合機能(パラメータを渡すために必要)のonClick = {()=> this.handleClick(インデックス)}
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
list: [
{
id: 1,
title: "学习react",
isLike: false
}
]
};
}
handleClick(index) {
console.log(index);
}
render() {
const { list } = this.state;
return (
<div>
<ul>
{list.map((item, index) => (
<li key={item.id} onClick={() => this.handleClick(index)}>
{item.title}
</li>
))}
</ul>
</div>
);
}
}
export default App;
第二:矢印関数はパラメータを渡す必要はない()=> this.handleClick
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
list: [
{
id: 1,
title: "学习react",
isLike: false
}
]
};
}
handleClick() {
console.log(10);
}
render() {
const { list } = this.state;
return (
<div>
<ul>
{list.map((item, index) => (
<li key={item.id} onClick={() => this.handleClick()}>
{item.title}
</li>
))}
</ul>
</div>
);
}
}
export default App;
第三:建設コンストラクタ、その後バインド、この(推奨)、パフォーマンス上の問題がある機能を矢印
あなたが書いていない場合でも、this.handleClick = this.handleClick.bind(本)、以前にサポートされますが、それは、新しいバージョンではない アプリケーションが反応作成 支援テンプレートを持っています
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
list: [
{
id: 1,
title: "学习react",
isLike: false
}
]
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
console.log(10);
}
render() {
const { list } = this.state;
return (
<div>
<ul>
{list.map((item, index) => (
<li key={item.id} onClick={this.handleClick}>
{item.title}
</li>
))}
</ul>
</div>
);
}
}
export default App;
第四は:矢印または機能(推奨)、このようなアプローチがされているバベルのサポート、およびリアクト作成アプリケーション テンプレートも、このようなアプローチをサポートしています
import React, { Component } from "react";
class App extends Component {
constructor(props) {
super(props);
this.state = {
list: [
{
id: 1,
title: "学习react",
isLike: false
}
]
};
}
handleClick = () => {
console.log(10);
};
render() {
const { list } = this.state;
return (
<div>
<ul>
{list.map((item, index) => (
<li key={item.id} onClick={this.handleClick}>
{item.title}
</li>
))}
</ul>
</div>
);
}
}
export default App;
PS:デフォルトの動作でpreventDefault()を防ぎます。
class Popper extends React.Component{
constructor(){
super();
this.state = {name:'Hello world!'};
}
preventPop(name, e){ //事件对象e要放在最后
e.preventDefault();
alert(name);
}
render(){
return (
<div>
<p>hello</p>
{/* Pass params via bind() method. */}
<a href="https://reactjs.org" onClick={this.preventPop.bind(this,this.state.name)}>Click</a>
</div>
);
}
}