【问题标题】:Can I simulate a change event using an input ref in React?我可以在 React 中使用输入引用来模拟更改事件吗?
【发布时间】:2022-11-17 18:05:29
【问题描述】:

所以,我有一个看起来像这样的组件:

  <Parent>
    <Sibling1 onChange={() => onChangeThatChangesParent}/> (Searchbar component that renders an input)
    <Sibling2 onClick={() => clearSearchbar}/> (button)
  </Parent>

兄弟姐妹1

const Sibling1 = ({onChangeThatChangesParent}) => {

  const handleChangeInternal = () => {
    onChangeThatChangesParent()
    otherFunctions()
  }
      return (
        <input onChange={handleChangeInternal}/>
      )
    }

在哪里兄弟姐妹1是一个呈现一个组件输入兄弟姐妹2是一个按钮.单击按钮时,我需要在输入上触发 onChange 事件。我想到的方法是将引用从 Parent 传递给 Sibling1,并在按下按钮时手动触发更改事件。

这可能吗?在这种情况下我如何触发更改事件?

请注意,我不能只使用 Ref 设置输入值,因为在触发 Sibling1 中的更改事件时,会执行一些其他功能。

提前致谢!

【问题讨论】:

  • 如果input上有onChange={handleChange},有什么理由不让按钮在点击时运行handleChange
  • 因为Sibling1组件内部有一个handler函数,执行来自parent的onChange,同时也执行其他内部函数。我需要一种从 Sibling1 外部触发更改事件的方法。为了更清楚,我将更改示例

标签: reactjs typescript use-ref react-ref


【解决方案1】:

我相信这个问题回答了您想要做的事情:
What is the best way to trigger onchange event in react js

您应该查看@Grin 接受的 awnser

【讨论】:

  • 这确实有效!这不是这样做的“反应方式”,但这是实现我所需要的唯一方式。谢谢!
猜你喜欢
  • 2020-07-21
  • 2011-09-06
  • 2023-01-26
  • 2011-08-09
  • 2022-01-15
  • 1970-01-01
  • 2017-12-11
  • 1970-01-01
  • 2011-01-05
相关资源
最近更新 更多