【问题标题】:use state of other class使用其他类的状态
【发布时间】:2020-05-25 22:55:54
【问题描述】:

我目前正在做一个学校项目。我有一个地图位置应用程序。但不知何故,我需要传递状态值坐标。但是我不能把它分享到下一堂课……有人可以帮我吗?

代码:

import React from 'react';
import '../style/card.css';
import '../js/functions/maps';
import Button from './button.js';
import { getLocation } from './functions/getLocation.js';
import './functions/maps';



class Mobile extends React.Component {
  state = {
    coordinates: {}
  };

  getLocationCoordinates = () => {
    getLocation((coordinates) => {
      this.setState({ coordinates });
      console.log(this.state.coordinates);
    });
  };

  functionCoordinatePrint = (index) => {
    return this.state.coordinates[index] ? this.state.coordinates[index] : Math.random() * 50 + 1;
  };

  render() {
    const { lat, lng } = this.state.coordinates;
    return (
      <div id={'location'} className={'card'}>
        <div className={'card-layout'}>
          <div className={'text-card'}>
            <h1>{this.props.header}</h1>
            {this.props.text !== '' && <p className={'max-width-70'}>{this.props.text}</p>}
            <div
              style={{
                color: 'var(--color-text)'
              }}
            >
              <input type="checkbox" id="conditions-read" />
              <a href="../pages/algemene-voorwaarden">Accepteer voorwaarden</a>
            </div>

            <Button function={this.getLocationCoordinates} text={'Allow Location'} />
            <p>{this.props.coordinaten}</p>
          </div>
          <div className={'mobile'}>
            <img src={this.props.device} className={'device'} alt={this.props.alt_image} />
            <div className={'overlay'}>
              <div id={'location-maps'}>
                <iframe
                  title="map"
                  frameBorder="0"
                  scrolling="no"
                  marginHeight="0"
                  marginWidth="0"
                  src={`https://www.mapquest.com/near-${this.functionCoordinatePrint(
                    'latitude'
                  )},${this.functionCoordinatePrint('longitude')}?zoom=3`}
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
  coordinatesToArray = coordinatesToArray[
    (this.functionCoordinatePrint('latitude'), this.functionCoordinatePrint('longitude'))
  ];
}

class Laptop extends React.Component {
  render() {
    return (
      <div id={'recommendations'} className={'card'}>
        <div className={'card-layout'}>
          <h1>{this.props.header}</h1>

          <div className={'laptop'}>
            <img
              style={{
                width: '150%'
              }}
              src={this.props.device}
              alt={this.props.alt}
            />
            <div className={'overlay-laptop'}>
              <div className={'maps'}>
                <iframe
                  title="mapExample"
                  frameBorder="0"
                  scrolling="no"
                  marginHeight="0"
                  marginWidth="0"
                  src={
                    'https://www.mapquest.com/near-' +
                    (this.props.lat ? this.props.lat : Math.random() * 30 + 1) +
                    ',' +
                    (this.props.long ? this.props.long : Math.random() * 30 + 1) +
                    '?zoom=3'
                  }
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export { Mobile, Laptop };

我尝试使用 props.state.coordinates[0],我还使用了全局变量,并在函数 GetLocation() 中设置了值,然后将其用于我的笔记本电脑版本。但是有人可以帮助我吗?

提前致谢。

【问题讨论】:

  • 您能否通过添加以下信息来改进您的答案:1. 组件的结构 2. 包含状态的组件 3. 需要使用状态的组件。
  • @SorcererApprentice 这些是我的卡片。在我的 App.js 中,我包含了这些笔记本电脑和移动版本。手机有手机png,笔记本有笔记本png。与彼此的地图位置。但是在移动卡中,您可以访问位置。然后你得到经度和纬度
  • 您要将数据传递到哪个类?您可以简单地执行 然后在MyComponent 中您可以使用this.props.data 访问它。还是我错过了什么?
  • @RahulDwivedi 我在移动组件中有数据,而不是在应用程序(全局组件)中,因为我想要移动组件中的按钮访问该位置,然后在笔记本电脑组件中添加值
  • 那么,如果我理解正确,您只想将您的位置信息传递到您的laptop 组件中?

标签: javascript reactjs jsx


【解决方案1】:
  1. 首先将移动设备和笔记本电脑这两个组件分离到单独的文件中。他们有自己的状态要管理,这样做,您的代码将更易于管理。 那么
  2. Laptop 组件导入mobile 组件。
  3. 将数据传递到笔记本电脑组件,例如, &lt;Laptop data={this.state.coordinates}/&gt;

  4. 在您的笔记本电脑组件中获取此信息, this.props.data

【讨论】:

  • 这是一种干净的方法吗?
  • 当然可以。您想将数据从mobile 传递到laptop 组件。因此您应该将它们分开并相应地传递。
  • 是的,但您可能也可以执行“提升状态”选项?
  • @user12380607 当laptopmobile 都从单个组件接收数据时,这是可取的。但是,在这种情况下,mobile 负责将数据发送到laptop 组件。
  • 我想我应该稍微清理一下我的代码...我应该用按钮创建一个函数并将其包含在 Mobile 中,但数据会转到 App 组件
【解决方案2】:

最简单的方法是通过 props 将数据向下传递。如果笔记本电脑和手机是兄弟姐妹,那么您需要将状态“提升”到一个公共父组件,然后您可以在那里管理状态并使用道具将其传递给每个孩子,例如

&lt;Mobile myState={myStateVariable} /&gt; &lt;Laptop myState={myStateVariable} /&gt;

【讨论】:

  • 但我的价值观是在移动组件而不是应用组件中
  • 它说 this.props.functionCoordinatesPrint 不是函数
  • 要么你需要让一个成为另一个的孩子,这样你就可以将道具传递给孩子,或者你需要将你的值提升到父组件并将值和函数传递给你的子组件。请参阅此内容以供参考reactjs.org/docs/lifting-state-up.html。或者,您可以使用上下文或状态框架(例如 redux),然后您可以在其中管理您的状态,并且任何组件都可以使用它。
【解决方案3】:

在这种情况下可能对您有所帮助的是Higher Order Component,或简称为 HOC。您可以将 HOC 视为可以存储坐标的父组件。子组件(在您的情况下为移动设备和笔记本电脑)可以设置和访问 HOC 中的数据,从而允许子组件呈现坐标。

让我们更详细地澄清这一点。首先,您需要创建一个将坐标保持在其状态的 HOC 组件。 HOC 应该有一个 setter,需要作为属性传递给子组件。坐标的值也应该传递给子组件,我们可以使用spread operator

const withCoordinates = (WrappedComponent) => {
    class WithCoordinates extends Component {
        constructor(props) {
            super(props);
            this.state = {
              coordinates: [],
            };
          }

          setCoordinates = (event) => {
            const { name, value } = e.target;
            this.setState({ [name]: value });    
          }

          render() {
              return (
                    <WrappedComponent
                      setCoordinates={(coordinates) => this.setCoordinates(coordinates)}
                      {...this.state}
                    />
              );
          }
    }

    return WithCoordinates;
}

export default withCoordinates;

接下来,我们需要连接子组件,以便它可以访问 HOC 定义的值。由于我们通过属性传递了coordinates 值和setCoordinates 方法,因此我们可以在子组件中访问它们。

class Laptop extends Component {
    render() {
        const { setCoordinates, coordinates } = this.props;

        return (
            <>
                <input name='coordinates' value={coordinates || ''} onChange={(e) => setCoordinates(e)} />
                <p>The coordinates are {coordinates}</p>
            </>
        );
    }
}

export default WithCoordinates(Laptop);

请注意,子组件与包裹在其周围的WithCoordinates 组件一起导出。这使得子组件可以访问 HOC 中的值。子组件中输入字段的名称对应于 HOC 中设置的状态值。

不要忘记使用Proptypes library 验证道具。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 2021-08-04
    • 1970-01-01
    相关资源
    最近更新 更多