在父级中触发点击事件后如何从父级访问子级状态?
我使用的是模式组件,这就是事件未从子组件触发的原因。
const Parent = () => {
...
return (
<Modal
saveHandler={ () => {
// Get child state here to do some stuff with
}} ... >
<Child ... />
</Modal>
)
}
const Child = () => {
const [state, dispatch] = useReducer(reducer, []);
...
}
答案 0 :(得分:3)
您可以使用带有useImperativeHandle
的Ref来允许父级访问子级状态
const Parent = () => {
const childRef = useRef(null);
...
return (
<Modal
saveHandler={ () => {
// Get child state here to do some stuff with
console.log(childRef.current.state);
}} ... >
<Child ref={childRef} ... />
</Modal>
)
}
const Child = (props, ref) => {
const [state, dispatch] = useReducer(reducer, []);
useImperativeHandle(ref, () => ({
state
}), [state])
...
}
export default forwardRef(Child);
尽管您可以使用上面的代码执行所需的操作,但建议您将状态提升到父组件并将其作为道具传递给子组件
const Parent = () => {
const [state, dispatch] = useReducer(reducer, []);
...
return (
<Modal
saveHandler={ () => {
// Get child state here to do some stuff with
console.log(state);
}} ... >
<Child state={state} dispatch={dispatch} ... />
</Modal>
)
}
const Child = ({state, dispatch}) => {
...
}
答案 1 :(得分:0)
如果您可以使用孩子传递点击事件,您可以像这样轻松地将数据从孩子传递给父母...
const dispatch = (stateOfChild) => {
// do something
}
return (
<Modal
<Child propsName = {stateOfChild => dispatch(stateOfChild)} />
</Modal>
)
还有孩子
const Child = () => {
return (
<div
onClick= {() => props.propsName(stateOfChild)} ></div>
)
}