【问题标题】:can we pass the setValue directly to onChange instead of wrapping it in a callback function我们可以将 setValue 直接传递给 onChange 而不是将其包装在回调函数中吗
【发布时间】:2021-10-18 04:16:32
【问题描述】:
function Parent() {
    const [value, setValue] = React.useState("");

    function handleChange(newValue) {
      setValue(newValue);
    }

    // We pass a callback to Child
    return <Child value={value} onChange={handleChange} />;
}


function Child(props) {
    function handleChange(event) {
        // Here, we invoke the callback with the new value
        props.onChange(event.target.value);
    }
  
    return <input value={props.value} onChange={handleChange} />
}

这里是参考文章https://webomnizz.com/change-parent-component-state-from-child-using-hooks-in-react。我的问题是我们是否可以直接将 setValue 传递给子组件的 onChange ?哪种方式是最佳实践?谢谢

function Parent() {
    const [value, setValue] = React.useState("");

    // We pass setValue directly to Child
    return <Child value={value} onChange={setValue} />;
}

【问题讨论】:

  • 当然可以,甚至更易读

标签: reactjs callback


【解决方案1】:

第二个最好的方法

function Parent() {
    const [value, setValue] = React.useState("");

    // We pass setValue directly to Child
    return <Child value={value} onChange={setValue} />;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-06
    • 2020-12-09
    • 1970-01-01
    • 2017-01-25
    • 1970-01-01
    • 2011-05-20
    • 2020-08-30
    相关资源
    最近更新 更多