从其他组件中的 React 组件调用函数
Call function from React component in other component
你能帮帮我吗?
我有两个功能组件,我需要在第二个组件中使用第一个组件的功能。
我想在 onClicked 函数中使用函数“sayHello”,但我不知道该怎么做。
import React from 'react';
type Props = {
}
const Component_1: React.FunctionComponent<Props> = () => {
const sayHello = () => {
console.log('----Hello');
}
return (
<div className="">
Component 1
</div>
);
};
export default React.memo(Component_1);
const Component_2: React.FunctionComponent<Props> = () => {
const onClicked = () => {
//How ???
//Component_1.sayHello()
}
return (
<div className="">
<div onClick={onClicked}>
Click me
</div>
<Component_1/>
</div>
);
};
const Component_1 = (props) => {
const sayHello = () => {
console.log("----Hello");
};
props.onClicked(sayHello);
return <div className="">Component 1</div>;
};
const Component_2 = () => {
let sayHello;
const fn = function (sayHelloFromComp1) {
sayHello = sayHelloFromComp1;
};
const onClicked = (e) => {
//How ???
//Component_1.sayHello()
sayHello();
};
return (
<div className="">
<div onClick={onClicked}>Click me</div>
<Component_1 onClicked={fn} />
</div>
);
};
export default Component_2;
你能帮帮我吗? 我有两个功能组件,我需要在第二个组件中使用第一个组件的功能。 我想在 onClicked 函数中使用函数“sayHello”,但我不知道该怎么做。
import React from 'react';
type Props = {
}
const Component_1: React.FunctionComponent<Props> = () => {
const sayHello = () => {
console.log('----Hello');
}
return (
<div className="">
Component 1
</div>
);
};
export default React.memo(Component_1);
const Component_2: React.FunctionComponent<Props> = () => {
const onClicked = () => {
//How ???
//Component_1.sayHello()
}
return (
<div className="">
<div onClick={onClicked}>
Click me
</div>
<Component_1/>
</div>
);
};
const Component_1 = (props) => {
const sayHello = () => {
console.log("----Hello");
};
props.onClicked(sayHello);
return <div className="">Component 1</div>;
};
const Component_2 = () => {
let sayHello;
const fn = function (sayHelloFromComp1) {
sayHello = sayHelloFromComp1;
};
const onClicked = (e) => {
//How ???
//Component_1.sayHello()
sayHello();
};
return (
<div className="">
<div onClick={onClicked}>Click me</div>
<Component_1 onClicked={fn} />
</div>
);
};
export default Component_2;