onClick不工作React js [英] onClick not working React js
问题描述
我试图在用户点击div时调用一个函数(使用onClick in react)。此时我不需要传递任何参数,只需要调用该函数即可。我很反应。因为我的无知,所以请提前道歉。谢谢。
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.
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'));
推荐答案
如果您的构建系统支持babel,请使用ES6反应代码中的箭头函数。
If your build system has support for babel, Use ES6 arrow functions in your react code.
如果使用ES6类创建组件,请在构造函数级别使用方法绑定以避免在每次渲染调用时绑定,并提供map函数中div标签的键。
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.
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>
这篇关于onClick不工作React js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!