【发布时间】:2017-01-03 00:19:24
【问题描述】:
我目前正在尝试编写一个可以执行以下操作的 React 应用程序: - 使用 map 函数从数组中创建问题列表。 - 使用 onClick 道具使每个列表元素可点击 - 链接的 onClick 方法使用我的 'qsChange' 属性更改另一个文件中的状态。
我很难让我的列表可点击并最终按照这个问题进行管理:React: trying to add an onClick to a li tag but the click handler function is undefined
但是,现在我无法让我的变量“选择”返回一个定义的值。我希望 var 选择等于“A ?”,“B ?”或“C?”取决于哪个
这是我的代码:
var questions = ["A ?", "B ?", "C ?"];
var Questions = React.createClass({
handleClick: function() {
var visibility;
if(this.props.visibility) {
document.getElementById('second').style.display = 'none';
visibility = false;
this.props.onChange(visibility);
} else {
document.getElementById('second').style.display = 'block';
visibility = true;
this.props.onChange(visibility);
}
},
/* Here is where my problem lies */
onItemClick: function(e){
var choice = e.target.key;
this.props.qsChange(choice);
alert(choice);
},
render: function() {
return (
<div className="bigqs">
<div id="first" className="small" style={firstStyle}>
<h1>Question :</h1>
<button style={btnStyle} onClick={this.handleClick}>
<img id="arrow" src="../../img/arrow.png" />
</button>
<h3 id="selectedQuestion">{this.props.selected}</h3>
</div>
<div id="second" className="small" style={{display: 'none'}}>
<h4>
<ul>
{questions.map(function(qs, i) {return <li key={qs[i]} onClick={this.onItemClick}>{qs}</li>;}, this)}
</ul>
</h4>
</div>
</div>
);
}
});
我还是个新手,所以请放纵 ;-) 我希望我已经足够清楚了。
Ps:我也试过这个指南,但它对我不起作用:http://derpturkey.com/react-pass-value-with-onclick/
【问题讨论】:
-
不要费心去获取密钥,只需将问题作为另一个参数传递
onClick={event => this.onItemClick(event, qs)} -
@azium :如果我这样做,我不知道应该在 onItemClick 中使用什么语法。你能帮帮我吗?
-
添加了答案
标签: javascript arrays function reactjs