如何在 ReactJS 函数组件中触发子方法
How to Trigger child method in ReactJS Functional Component
我有一些内联编辑字段,单击保存应该会触发子方法,该方法会使用其他属性执行 API 调用。目前使用useState来设置flag,但是只用了一次,如果我重新提交就不行了,我想改用这个方法。
useImperativeHandle
js useImperativeHandle(ref, createHandle, [deps])
useImperativeHandle
customizes the instance value that is exposed to
parent components when using ref
. As always, imperative code using
refs should be avoided in most cases. useImperativeHandle
should be
used with forwardRef
:
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
} })); return <input ref={inputRef} ... />; }
FancyInput = forwardRef(FancyInput);
In this example, a parent component that renders <FancyInput
ref={inputRef} />
would be able to call inputRef.current.focus()
.
只是想添加一个可重复使用 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>
}
我有一些内联编辑字段,单击保存应该会触发子方法,该方法会使用其他属性执行 API 调用。目前使用useState来设置flag,但是只用了一次,如果我重新提交就不行了,我想改用这个方法。
useImperativeHandle
js useImperativeHandle(ref, createHandle, [deps])
useImperativeHandle
customizes the instance value that is exposed to parent components when usingref
. As always, imperative code using refs should be avoided in most cases.useImperativeHandle
should be used withforwardRef
:useImperativeHandle(ref, () => ({ focus: () => { inputRef.current.focus(); } })); return <input ref={inputRef} ... />; } FancyInput = forwardRef(FancyInput);
In this example, a parent component that renders
<FancyInput ref={inputRef} />
would be able to callinputRef.current.focus()
.
只是想添加一个可重复使用 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>
}