Javascript 如何在React.js中将事件函数分配给DOM列表
我想问一下如何在React.js中使用事件函数 我想做一个测试函数,当点击标题列表的时候,它会得到索引和打印索引。 但单击时此函数不起作用 你能给我一些解决问题的建议吗Javascript 如何在React.js中将事件函数分配给DOM列表,javascript,reactjs,event-handling,Javascript,Reactjs,Event Handling,我想问一下如何在React.js中使用事件函数 我想做一个测试函数,当点击标题列表的时候,它会得到索引和打印索引。 但单击时此函数不起作用 你能给我一些解决问题的建议吗 const some = (props) = { // 'props' have two attributes, titles and contents // which each is a array of strings. function test(index){ consol
const some = (props) = {
// 'props' have two attributes, titles and contents
// which each is a array of strings.
function test(index){
console.log('clicked');
console.log(index);
}
const titlesList = props.titles.map((title, index) => {
return <div className="eachTitle"
key={index}
onClick={test(index)}>
{title} {index}
</div>
});
return (
<div>
{titlesList}
</div>
);
}
const some=(道具)={
//“道具”有两个属性,标题和内容
//每个都是一个字符串数组。
功能测试(索引){
console.log('clicked');
控制台日志(索引);
}
常量标题列表=道具.标题.地图((标题,索引)=>{
返回
{title}{index}
});
返回(
{标题列表}
);
}
谢谢你的阅读 当呈现组件时,它实际上会调用
test(index)
。这将onClick
的值设置为test(index)
的返回值。您要做的是将onClick设置为一个函数,该函数使用适当的参数调用您想要的任何东西
onClick={()=>{test(index)}}
这是一个匿名函数,可以传递。单击时,将调用匿名函数,它实际上只是使用参数调用test(index)
。如果您不需要将任何参数传递给test
,您可以执行以下操作:
onClick={test}
因为您不能告诉onClick传递参数(除了事件对象之外),所以匿名函数是一种简单的方法 这里的问题在于绑定,有两种方法可以解决它,一种是@Jtcruthers使用匿名函数提到的,另一种方法是在调用use this时创建构造函数并使用
.bind()
注册方法
onClick={this.test(index)}
功能测试(索引){
console.log('clicked');
控制台日志(索引);
}
常量标题列表=道具.标题.地图((标题,索引)=>{
返回
{title}{index}
});
try onClick={()=>test(index)}你应该将Jtcruthers的答案标记为正确,因为他花了时间来实际回答。:)谢谢你的回答和努力!谢谢你的解释。
constructor(props){
super(props);
this.test = this.test.bind(this);
}
function test(index){
console.log('clicked');
console.log(index);
}
const titlesList = props.titles.map((title, index) => {
return <div className="eachTitle"
key={index}
onClick={this.test(index)}>
{title} {index}
</div>
});