【发布时间】: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 中的所有值)
【问题讨论】:
-
您将在父(或最高级别)组件中设置您的状态,并为您正在操作的任何内容传递对重置方法的引用。在您的父组件(您在其中调用子组件)中,您可以将重置函数作为道具传递给您的孩子。例如:(在您的更高级别返回):
<Childcomponent resetValue={restart} />然后您可以从您的子组件内部调用它。您在 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