Javascript onClick 不工作 React js
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38401902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
onClick not working React js
提问by Viper
I am trying to call a function when a user clicks a div (using onClick in react). I don't need to pass any arguments at this moment, just need to call the function. I'm fairly new to react.js so apologies in advance for my ignorance. Thanks.
我试图在用户单击 div 时调用一个函数(在反应中使用 onClick)。我此时不需要传递任何参数,只需要调用函数即可。我对 react.js 还很陌生,所以提前为我的无知道歉。谢谢。
var Test = React.createClass({
btnTapped: function(){
console.log('tapped!');
},
render: function() {
var stationComponents = this.props.stations.map(function(station, index) {
return <div onClick={btnTapped()}><img src="img/test.png" />{station}</div>;
});
return <div>{stationComponents}</div>;
}
});
var cards = ["amazon", "aeo", "aerie", "barnes", "bloomingdales", "bbw","bestbuy", "regal", "cvs", "ebay", "gyft", "itunes", "jcp", "panera", "staples", "walmart", "target", "sephora", "walgreens", "starbucks"];
ReactDOM.render(<Test stations={cards} />, document.getElementById('test-div'));
采纳答案by Galeel Bhasha
If your build system has support for babel, Use ES6 arrow functions in your react code.
如果您的构建系统支持 babel,请在您的 React 代码中使用 ES6 箭头函数。
If you are using ES6 class for creating components, use method binding at the constructor level to avoid binding at every render call and also provide a key to the div tag inside the map function.
如果您使用 ES6 类来创建组件,请在构造函数级别使用方法绑定以避免在每次渲染调用时进行绑定,并在 map 函数内为 div 标签提供一个键。
class Test extends React.Component {
constructor(props) {
super(props);
this.btnTapped = this
.btnTapped
.bind(this);
}
btnTapped() {
console.log('tapped');
}
render() {
return (
<div>
{this
.props
.stations
.map((station, index) => {
return <div key={index} onClick={this.btnTapped}>{station}</div>
})
}
</div>
)
}
}
var cards = ["amazon", "aeo", "aerie", "barnes", "bloomingdales", "bbw", "bestbuy", "regal", "cvs", "ebay", "gyft", "itunes", "jcp", "panera", "staples", "walmart", "target", "sephora", "walgreens", "starbucks"];
ReactDOM.render(
<Test stations={cards}/>, document.getElementById('test-div'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<body>
<div id="test-div"></div>
</body>
回答by Alexandr Lazarev
You should set a function to onClick
attribute, not call it.
Should be: onClick={this.btnTapped}
instead of onClick={btnTapped()}
.
您应该将函数设置为onClick
属性,而不是调用它。应该是:onClick={this.btnTapped}
而不是onClick={btnTapped()}
。
Also, it is possible to do like this:
此外,可以这样做:
<div
onClick={function(e) {
this.btnTapped(); //can pass arguments this.btnTapped(foo, bar);
}}
>
It's usually used when you need to pass an argument to your function.
当您需要将参数传递给函数时,通常会使用它。
Also, to be able to get component's context from the external function, you should use bind(this)
method. Like: onClick={btnTapped.bind(this)}
此外,为了能够从外部函数获取组件的上下文,您应该使用bind(this)
方法。喜欢:onClick={btnTapped.bind(this)}
And since you are using a scope function for mapping array, new context is created inside of: this.props.stations.map(function(station, index){}
. And this
is overridden. Just use an arrow functioninstead:
而且,由于使用的是映射数组范围功能,在内部创造了新的语境:this.props.stations.map(function(station, index){}
。并且this
被覆盖。只需使用箭头函数:
var stationComponents = this.props.stations.map((station, index) => {
return <div onClick={this.btnTapped}><img src="img/test.png" />{station}</div>;
});
回答by maheshmnj
Note: Not a reactjs Expert :)
注意:不是 reactjs 专家 :)
I am exploring reactjs right now and as of version 16.3.1
the arrow function worked for me
我现在正在探索 reactjs 和 version 16.3.1
箭头功能对我有用
<button
onClick={() => { console.log("button clicked");}}>
button
</button>
回答by Vitaly Kravtsov
You missed this
keyword before function. Also you must provide function but not calling it
您this
在函数之前错过了关键字。此外,您必须提供功能但不调用它
<div onClick={this.btnTapped}>
<div onClick={this.btnTapped}>
UPDATE:
更新:
You missed that you are redefines this
in map callback function.
您错过了this
在地图回调函数中重新定义的信息。
Use arrow function
使用箭头功能
this.props.stations.map((station, index) => {
return <div onClick={this.btnTapped}><img src="img/test.png" />{station}</div>;
});
or bind context to function
或将上下文绑定到函数
this.props.stations.map(function (station, index) {
return <div onClick={this.btnTapped}><img src="img/test.png" />{station}</div>;
}.bind(this));
回答by Kishore Ganesan
Whenever you want to use a function in the render method, first you need to bind those methods in the constructor. One more thing is when you don't want to pass any arguments to the methods that you need to call use this onClick = {this.btnTapped}
instead of onClick = {this.btnTapped()}
. Thank you.
每当你想在 render 方法中使用一个函数时,首先你需要在构造函数中绑定这些方法。还有一件事是,当您不想将任何参数传递给需要调用的方法时,请使用 thisonClick = {this.btnTapped}
而不是onClick = {this.btnTapped()}
. 谢谢你。
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
export default class Test extends Component {
constructor (props) {
super(props);
//set cards value in state then you don't need to use props...
this.state = {
cards: ["amazon", "aeo", "aerie", "barnes", "bloomingdales",
"bbw","bestbuy", "regal", "cvs", "ebay", "gyft", "itunes",
"jcp", "panera", "staples", "walmart", "target", "sephora",
"walgreens", "starbucks"]
}
this.btnTapped = this.btnTapped.bind(this);
// bind all the methods which you're using the "this.state" inside it....
}
btnTapped (card) {
console.log("Coming here:::" + card)
}
render() {
var cards = this.state.cards
return (
<div>
{/* if you don't want to pass an arguments use this... */}
{
cards.map((card, i) =>
<button key = {i} onClick = {this.btnTapped}>{card}</button>
)
}
{/* if you want to pass arguments use this */}
{
cards.map((card, i) =>
<button key = {i} onClick = {(e) => this.btnTapped(card)}>{card}</button>
)
}
</div>
);
}
}
ReactDOM.render(<Test />, document.getElementById('test-div'));