const initialValue_modalProps = [
{ show: false, response: "" }
];
const [modalProps, setModalProps] = useState(initialValue_modalProps)
const passedFunction = () => {
setModalProps(modalProps => initialValue_modalProps);
}
..
..
<div>
<Modal show={modalProps.show}
response={modalProps.response}
passedFunction={passedFunction}></Modal>
</div>
export default function ModalComp(props) {
const [modalOpen, setmodalOpen] = useState(true);
console.log('modalOpen', modalOpen);
if (props.show === false || modalOpen === false) {
return null;
}
return (<Modal isOpen={props.show}>
<ModalHeader>Deployment Status</ModalHeader>
<ModalBody>{props.response}</ModalBody>
<ModalFooter>
<Button onClick={() => {
setmodalOpen(modalOpen => false);
props.passedFunction();
}}>Close</Button>
</ModalFooter>
</Modal>)
}
在这里,我想将Function函数从Parent传递给child,以便Child组件可以执行它以重设父状态。
答案 0 :(得分:2)
您可以通过实时示例演示https://codesandbox.io/s/musing-mendeleev-6fvyx
将此作为参考。import functools
import itertools
class StopIteration1(RuntimeError):
pass
class map1(map):
def __new__(cls, func, iterable):
iterator = iter(iterable)
self = super().__new__(cls, func, iterator)
def __next__():
arg = next(iterator)
try:
return func(arg)
except StopIteration:
raise StopIteration1(0)
except StopIteration1 as error:
raise StopIteration1(int(str(error)) + 1)
self.__next__ = __next__
return self
def __next__(self):
return self.__next__()
# tuple(map1(tuple,
# [map1(next,
# [iter([])])]))
# ---> <module>.StopIteration1: 1
答案 1 :(得分:1)
您需要删除passedFunction
后面的括号,因为否则您将首先执行该函数,然后将结果传递给子级。通过passedFunction={passedFunction}
传递函数。
const ParentComponent = () => {
const initialModalProps = { ... };
const [modalProps, setModalProps] = useState(initialModalProps);
const passedFunction = () => {
setModalProps(initialModalProps);
}
return (
<div>
<Modal
show={modalProps.show}
response={modalProps.response}
passedFunction={passedFunction} />
</div>
);
};
答案 2 :(得分:0)
将子组件更改为此。及其工作方式
export default function ModalComp(props) {
//const [modalOpen, setmodalOpen] = useState(true);
if (props.show === false) {
return null;
}
return (<Modal isOpen={props.show}>
<ModalHeader>Deployment Status</ModalHeader>
<ModalBody>{props.response}</ModalBody>
<ModalFooter>
<Button onClick={props.passedFunction}>Close</Button>
</ModalFooter>
</Modal>)