如何在Yew函数组件中为onclick回调传递参数
在Yew函数组件中为onclick事件处理器传递参数的正确方式
你直接在onclick中调用handle_formula_click("fixed1")的写法是错误的——Yew的onclick期望接收一个Callback<MouseEvent>,而非直接执行函数。以下是两种正确的实现方案:
方案一:复用带参数的回调
先定义接收自定义参数的回调,再在onclick中通过闭包包装并传递参数:
#[function_component(Calculator)] pub fn calculator() -> Html { let navigator = use_navigator().unwrap(); // 定义接收字符串参数的回调 let handle_formula_click = Callback::from(move |id: String| { navigator.push(&AppRoute::Formula { id }); }); html! { <div> {/* 用闭包忽略默认的鼠标事件参数,调用回调的emit方法传递自定义参数 */} <button onclick={move |_| handle_formula_click.emit("fixed1".to_string())}> {"点击跳转到公式页面"} </button> </div> } }
方案二:直接在onclick中定义闭包
如果不需要复用回调逻辑,可直接在onclick内编写带参数的闭包:
#[function_component(Calculator)] pub fn calculator() -> Html { let navigator = use_navigator().unwrap(); let fixed_id = "fixed1".to_string(); html! { <div> <button onclick={move |_| { // 直接在闭包中使用捕获的参数 navigator.push(&AppRoute::Formula { id: fixed_id.clone() }); }}> {"点击跳转到公式页面"} </button> </div> } }
关键注意事项
onclick默认会传递MouseEvent参数,不需要时可以用_忽略。- 使用
Callback时,必须通过emit方法传递自定义参数,不能直接调用回调函数。 - 注意move闭包的所有权问题:若捕获的变量需要被多个组件复用,记得用
clone复制变量,避免所有权转移导致的编译错误。
内容的提问来源于stack exchange,提问作者Jon Ham
相关产品推荐
相关产品推荐

