gpt4 book ai didi

javascript - REACTJS:在另一个类中更改状态

转载 作者:行者123 更新时间:2023-11-30 09:29:13 24 4
gpt4 key购买 nike

我有两个 Reactjs 文件
文件1.js

class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
selection: null
};

文件2.js

class SearchBar extends Component {
InputChange = () => {
console.log(App.state);
}}

我想在使用 SearchBar 类时使用和更改 App 类的状态,我将 file2 导入到 file1。谢谢你!我的英语不好。

最佳答案

这很简单 :D 你只需要像这样传入改变状态的函数:

class App extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
selection: null
};

changeStuff(paramsIfAny) {
this.setState(/* whatever you want */);
}

render() {
.....
<SearchBar changeHandler={this.changeStuff.bind(this)} />
.....
}
}

然后在您的 SearchBar 组件上

class SearchBar extends Component {
InputChange = (params) => {
this.props.changeHandler(params);
}}

这实际上是简化代码以简化我的意思。我希望你知道它是如何完成的!

关于javascript - REACTJS:在另一个类中更改状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47410326/

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