[英]How can i call/execute function of functional component outside react?
[英]Can I call a function in a different React component?
我可以在不同的 React 组件中调用 function 吗?
例如,
--index.js--
<component1 />
<component2 />
---------------
当我在 Component1 中单击或向元素(例如文本输入)输入值时,我想关注 Component2 中的按钮
可能吗?
您可以将父道具传递给两个组件。 例如:
class Parent {
state = {
fieldFocus: false
}
handleFocus = () => {
this.setState({ focus: true });
}
render() {
const { focus } = this.state;
return (
<>
<component1 handleFocus={this.handleFocus} />
<component2 isFocus={focus} />
</>
)
}
}
在组件 1 中:
class Component1 {
render() {
const { handleChange } = this.props;
return <button onClick={handleChange} />
}
}
然后在 component2 中,您将能够从父级访问 isFocus 道具并将其设置为焦点。
编辑
在组件 2 中:
class Component1 {
render() {
const { isFocus } = this.props;
return <input isFocus={isFocus} />
}
}
然后根据 boolean isFocus
编辑样式
如果您需要调用 static function,则可以将其分离为 function。 所以把这个 function 放到 utils 文件夹中,需要的时候再导入。 如果涉及任何 state,则传递或外部 state 管理
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.