【问题标题】:How to run function in App.js from component如何从组件运行 App.js 中的函数
【发布时间】:2021-07-06 23:26:16
【问题描述】:

对不起,我对 react.js 和 Javascript 很陌生,所以这可能是一个非常简单的答案,但看在上帝的份上。我找不到有效的答案。 在我的App.js 中,我有一个重置一些变量的简单方法。

App.js

import React, { Component } from 'react';
import KeyPress from './components/KeyPress';
...
const initialState = {
  text: GetText(),
  userInput: '',
  symbols: 0,
  sec: 0,
  started: false,
  finished: false
}
const ThemeContext = React.createContext(initialState);
class App extends Component {
  
  state = initialState;

  restart = () => {
    this.setState(initialState)
  }
...

在我的组件文件中,我有一个看起来像这样的结构。

KeyPress.js

import React, { Component } from 'react'

export class KeyPress extends Component {
    render() {
        return (
            <div>
                
            </div>
        )
    }
}

export default KeyPress

文件结构

src
├── App.js
├── components
    ├── GetText.js
    ├── KeyPress.js

我怎样才能从KeyPress.js 调用App.js 中的函数restart()(希望重置initialState 中的所有值)

【问题讨论】:

  • 您将在父(或最高级别)组件中设置您的状态,并为您正在操作的任何内容传递对重置方法的引用。在您的父组件(您在其中调用子组件)中,您可以将重置函数作为道具传递给您的孩子。例如:(在您的更高级别返回):&lt;Childcomponent resetValue={restart} /&gt;然后您可以从您的子组件内部调用它。您在 App 组件中设置状态是否有原因?是共享的吗?上下文可能会更好。
  • 是的,我考虑过使用上下文,但当时这远远超出了我的知识范围。谢谢你的信息,我会看看我能用它做什么。
  • 我得到了答案restart={restart}。这不起作用,因为我得到了src/App.js Line 61:41: 'restart' is not defined no-undef,即使我在App.js 中定义了restart
  • 您没有引用子组件中的道具。在您的孩子中重新启动是传递的 props 对象的一部分,因此您可以通过 const restart = this.props.restart 访问它 将 props 对象想象为从运营商(父母)留在邮箱中的邮件。通过调用 this.props.name,您将打开邮箱并抓取里面的内容。
  • 好的,这行得通。感谢您的精彩解释!

标签: javascript reactjs function-call


【解决方案1】:

有许多可能的解决方案:

  1. 假设KeyPress 是从App 内部渲染的,则将restart 函数作为道具传递,例如&lt;KeyPress restart={restart} /&gt;.

  2. Use the Context API to manually create a global state 或使用 Redux 之类的库。

【讨论】:

  • 我已经尝试了你的第一个解决方案,我得到了src/App.js Line 61:61: 'restart' is not defined no-undef
【解决方案2】:

在您的 App 类组件中,您将拥有:

restart = () => {
    this.setState(initialState)
  }
render() {
        return(
           <div>
            <KeyPress resetMethod={this.restart} />
           </div>
        );
    }

然后在 KeyPress.js 中:

render() {

return <button onClick={this.props.resetMethod}>Reset</button>;
}

【讨论】:

  • 嗯,即使我在 App.js 中将重启定义为函数,我也收到了 src/App.js Line 61:61: 'restart' is not defined no-undef
  • 我确实忘记了“this”,因为它应该是“this.restart”
  • 对我来说太疯狂了,人们仍然使用类组件。我已经很久没有使用它们了,我一直忘记构造函数和 this 绑定。啊。哈哈哈
  • 哦,你现在用什么?我是不是已经过时了。
  • @JoelHager - 由于需要维护的现有应用程序(技术债务),人们将在相当长的时间内使用类组件。而且学习它不需要太多时间。 BuddyBob - 功能性组件风靡一时。
【解决方案3】:

尝试从 app.js 导出函数,如果不起作用,则将其导入到 comp 在根目录中创建文件并从那里创建和导出函数

【讨论】:

  • 导出函数是什么意思?
猜你喜欢
  • 1970-01-01
  • 2014-04-03
  • 1970-01-01
  • 2021-04-25
  • 2017-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多