gpt4 book ai didi

javascript - React 在组件内部执行一个方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:40:53 25 4
gpt4 key购买 nike

我有这样一个组件:

import React, { Component } from 'react';

class MyComponent extends Component {

constructor(props, context) {
super(props, context);
this.state = {
isActive: false,
}
}

showMyComponent() {
this.setState({
isActive: true,
});
}

hideMyComponent() {
this.setState({
isActive: false,
});
}

render() {
return (
<div>
<h1>Compoent Here</h1>
</div>
);
}
}

export default MyComponent;

现在,我在 index.js 上添加了几个组件。

...

<Header />
<Nave />

我现在可以在这里做这样的事情吗:

MyComponent.showMyComponent();

就像您通常调用函数一样?

如果不是,这是怎么做到的?

最佳答案

您可以使用引用。在您的 render() 方法中,您可以获得 ref。例如

<MyComponent ref={ref => {this.myComponent = ref}}/>

您需要创建一个字段 myComponent 并将其分配给它。这样你就可以像 this.myComponent.showMyComponent()

这样调用它

请参阅此处 Refs and the DOM

关于javascript - React 在组件内部执行一个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43559948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com