【问题标题】:How to Trigger child method in ReactJS Functional Component如何在 ReactJS 功能组件中触发子方法
【发布时间】:2020-09-16 06:59:24
【问题描述】:

我有一些内联编辑字段,单击保存应触发子方法,该方法使用其他属性执行 API 调用。目前使用 useState 设置标志,但它只工作一次,如果我重新提交它不起作用,我想使用该方法。

【问题讨论】:

  • useImperativeHandle 能满足您的需要吗?
  • 您好!您能否发布您的代码(最好是minimally reproducible example),以便我们了解您到目前为止所做的尝试?

标签: reactjs react-hooks react-functional-component


【解决方案1】:

只是想添加一个可重复使用 useState 的答案。诀窍是使用不断变化的值而不是布尔值,并在值发生变化时采取行动:

function Parent() {
  const [signal, setSignal] = useState()

  const onClick = () => setSignal(Date.now()) // trigger the child to save

  return (
    <div>
      <Child signal={signal} />
      <button onClick={onClick}>Save</button>
    </div>
  }
}

function Child({signal}) {
  // send the data whenever signal changes
  useEffect(() => {
    if (signal != null) {
      sendData()
    }
  }, [signal])

  return <div>...</div>
}

【讨论】:

    【解决方案2】:

    来自documentation

    使用ImperativeHandle

    js useImperativeHandle(ref, createHandle, [deps])

    useImperativeHandle 自定义暴露的实例值 使用ref 时的父组件。与往常一样,命令式代码使用 在大多数情况下应避免使用 refs。 useImperativeHandle 应该是 与forwardRef一起使用:

    useImperativeHandle(ref, () => ({
        focus: () => {
          inputRef.current.focus();
        }   }));   return <input ref={inputRef} ... />; }
    
    FancyInput = forwardRef(FancyInput);
    

    在此示例中,呈现<FancyInput ref={inputRef} /> 的父组件将能够调用inputRef.current.focus()

    【讨论】:

    • 我是 ReactJS 新手,我试过这个,目前他的子组件还从父组件中选择一些选定的数据,例如 在此处添加“ref”时遇到问题,因为它抱怨 ref 不是有效的道具。
    • ref 像道具一样被分配,但在孩子中你需要使用forwardRef,如图所示。
    猜你喜欢
    • 2021-05-25
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 2015-07-25
    • 2017-08-21
    • 2020-11-03
    • 1970-01-01
    相关资源
    最近更新 更多