如何在ReactJS功能组件中触发子方法

时间:2020-05-28 20:02:46

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

我有一些内联编辑字段,单击“保存”将触发子方法,该子方法执行具有其他属性的API调用。当前正在使用useState来设置标志,但是它仅工作一次,如果我重新提交它不起作用,那么我想使用该方法。

2 个答案:

答案 0 :(得分:0)

documentation

useImperativeHandle

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()

答案 1 :(得分:0)

只想添加一个重复使用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>
}