Reactjs 我无法在react组件中传递onClick事件?
在这段代码中,我试图用relay修改我的组件,但我不知道为什么我不能将onClick事件放在列表上Reactjs 我无法在react组件中传递onClick事件?,reactjs,relayjs,Reactjs,Relayjs,在这段代码中,我试图用relay修改我的组件,但我不知道为什么我不能将onClick事件放在列表上 handleSubmit = (e) => { e.preventDefault(); Relay.Store.commitUpdate( new createTodoMutation({ text: this.refs.textForNewTodo.value, store: this.props.store })
handleSubmit = (e) => {
e.preventDefault();
Relay.Store.commitUpdate(
new createTodoMutation({
text: this.refs.textForNewTodo.value,
store: this.props.store
})
);
this.refs.textForNewTodo.value="";
}
handleOnClick = (id) => {
id.preventDefault();
Relay.Store.commitUpdate(
new toggleTodoStatus({
id: id,
store: this.props.store
})
);
}
render() {
let todolist = this.props.store.todoConnection.edges.map((edge) => {
return (
<li key={edge.node.id} onClick={this.handleOnClick(edge.node.id)}>
<p>{edge.node.text}</p>
</li>
);
});
return (
<div>
<h3>Todos</h3>
<form onSubmit={this.handleSubmit} >
<input type="text" placeholder="Todo text" ref="textForNewTodo" />
<button type="submit">Add</button>
</form>
Showing:
<select onChange={this.setLimit} defaultValue={this.props.relay.variables.limit}>
<option value="5">5</option>
<option value="10">10</option>
</select>
<ul>
{todolist}
</ul>
</div>
);
handleSubmit=(e)=>{
e、 预防默认值();
Relay.Store.commitUpdate(
新CreateTommutate({
text:this.refs.textForNewTodo.value,
商店:这个。道具。商店
})
);
this.refs.textForNewTodo.value=“”;
}
handleOnClick=(id)=>{
id.preventDefault();
Relay.Store.commitUpdate(
新扳机({
id:id,
商店:这个。道具。商店
})
);
}
render(){
让todolist=this.props.store.todoConnection.edges.map((edge)=>{
返回(
{edge.node.text}
);
});
返回(
待办事项
添加
显示:
5.
10
{托多利斯特}
);
handleSubmit正在工作,但handleOnClick-on-List没有工作,我有一个错误“Uncaught TypeError:无法读取未定义的属性'id',但我在通过onClick={this.handleOnClick(edge.node.id)}调用时传递edge.node.id。我看不出这段代码有什么问题。帮助?这是传递
onClick
事件的错误方式。如果执行onClick={this.handleOnClick(edge.node.id)}
,则在渲染期间只会调用一次事件
请尝试
onClick={()=>this.handleOnClick(edge.node.id)}
在您的情况下,在每次渲染后立即调用handleOnClick,而不是将其传递给onClick,以便在单击该元素时可以调用它
由于需要将参数传递给函数,因此不能简单地将函数传递给onClick
<... onClick={this.handleOnClick} />
为了解决这个问题,您可以创建一个arrow函数并将arrow函数传递给onClick
<... onClick={() => this.handleOnClick(edge.node.id)} />
this.handleon单击(edge.node.id)}/>
您也不需要id.preventDefault();再也没有了我仍然有未捕获的TypeError:无法读取未定义错误的属性“id:(@iamnewie这是来自
onClick
行的错误吗?这意味着您的边缘
没有名为节点
的属性。请尝试注销它?