对不起,我对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
如何从restart()
调用App.js
中的函数KeyPress.js
(希望重新设置initialState
中的所有值)
发布于 2021-07-06 15:39:28
在应用程序类组件中,您将拥有:
restart = () => {
this.setState(initialState)
}
render() {
return(
<div>
<KeyPress resetMethod={this.restart} />
</div>
);
}
然后在KeyPress.js中:
render() {
return <button onClick={this.props.resetMethod}>Reset</button>;
}
发布于 2021-07-06 15:39:50
有一些可能的解决办法:
KeyPress
是从App
内部呈现的,则将restart
函数作为支柱传递,例如<KeyPress restart={restart} />
。发布于 2021-07-06 15:32:34
尝试从app.js导出函数,导入它到comp,如果它没有工作,在根目录中创建一个文件,然后从那里创建和导出函数
https://stackoverflow.com/questions/68278384
复制相似问题