gpt4 book ai didi

javascript - 如何将变量从一个类传递到另一个类

转载 作者:行者123 更新时间:2023-11-29 20:49:00 25 4
gpt4 key购买 nike

好吧,所以我正在尝试简化我正在进行的项目,但在我在 Internet 上阅读的所有信息中,没有一个能回答我的问题。我的疑问是如何将变量(变量的名称及其值)从一个类传递到另一个类?我应该使用 Prop 吗?我应该做类似于 this.state.variable 的事情吗?如何做呢?我将编写一个示例代码只是为了更直观地展示我正在尝试做的事情,但这不是我的实际代码。感谢您的帮助:)

class FishInSea{
constructor(props){
super(props);
this.setState({fishInSea: 100});
}
render(){
return(
<div>Fish in the sea: {this.state.fishInSea}</div>
);
}
}

class FishInOcean{
constructor(props){
super(props);
this.setState({fishInOcean: <FishInSea this.props.fishInSea/> * 1000});
}
render(){
return(
<div>Fish in the ocean: {this.state.fishInOcean}</div>
);
}
}

export default FishInOcean;

最佳答案

您需要先将这两个类都放入 React 组件中。由于这两个类都修改了状态,因此它们被称为有状态组件。该类必须扩展 React 的基类,即组件。

在构造函数中,我们只进行状态初始化,但不会修改那里的状态。但是您正在修改不正确的状态。而是将 setState 移动到 componentDidMount。

假设在 FishInSea 类中你有 fishInSea,你想将它作为 props 传递给 FishInOcean 组件。

检查下面两个更正的组件,它们是如何从一个组件传递到另一个组件的

  import React, { Component } from “react”;
class FishInSea extends Component{
constructor(props){
super(props);
this.state = {
fishInSea: 100
}
}
componentDidMount(){
this.setState({fishInSea: 100});
}
render(){
const { fishInSea } = this.state;
return(
<div>Fish in the sea:
<FishInOcean fishInSea={fishInSea} />
</div>
);
}
}


import React, { Component } from “react”;
class FishInOcean extends Component{
constructor(props){
super(props);
this.state = {fishInOcean: 1000}
}
componentDidMount(){
this.setState({fishInOcean: 1000});
}
render(){
const { fishInOcean} = this.state;
const { fishInSea } = this.props;
return(
<div>Fish in the ocean: {fishInOcean}
{fishInSea}
</div>
);
}
}

export default FishInOcean;
/*There was a typo*/

关于javascript - 如何将变量从一个类传递到另一个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52866755/

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