Javascript React.js随机名称生成器未定义或编译失败

Javascript React.js随机名称生成器未定义或编译失败,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我肯定我这里有些不正确的地方,需要一些帮助。我试图从名为names的数组中返回一个随机名称,但是我写的东西工作不正常 我尝试使用GetRandomName随机访问数组并返回一个名称。我总是与数组打交道,并使用此练习来更加熟悉数组 我在我的父母中的代码是: import React, { Component } from 'react'; import styled from 'styled-components'; import { ContainLeft } from '../../../he

我肯定我这里有些不正确的地方,需要一些帮助。我试图从名为names的数组中返回一个随机名称,但是我写的东西工作不正常

我尝试使用GetRandomName随机访问数组并返回一个名称。我总是与数组打交道,并使用此练习来更加熟悉数组

我在我的父母中的代码是:

import React, { Component } from 'react';
import styled from 'styled-components';
import { ContainLeft } from '../../../helper/comps';
import Moment from 'react-moment';
import harry from '../../../../static/quotes-harry.jpg';
import { names, sayings } from './arrays';

const QuoteBox = styled.div`
  width: 500px;
  height: 250px;
  border: 1px solid white;
  background: black;
  display: flex;
`;

const QuoteHolder = styled.div`
  width: 250px;
  margin: 2em;
`;

const Quote = styled.p`
  color: white;
  width: 200px;
  font-size: 16px;
  font-weight: bold;
`;

const Author = styled.p`
  color: white;
  font-style: italic;
  font-size: 12px;
`;

const Image = styled.div`
  width: 150px;
  height: 200px;
  margin: 1em;
`;

class Container extends Component {
  constructor() {
    super();
    this.state = {};
  }
  getRandomName() {
    return names[Math.floor(Math.random() * (names.length - 1))];
  }
  render() {
    return (
      <ContainLeft
        style={{
          alignItems: 'center',
          position: 'absolute',
          width: '100%',
          margin: 0,
          marginTop: '5em',
          padding: 0,
          justifyContent: 'center'
        }}
      >
        <QuoteBox>
          <QuoteHolder>
            <Quote>"Lorem Ipsum Dolor Set Amet, Some other Words Quote"</Quote>
            <Author>{getRandomName}</Author>
          </QuoteHolder>
          <Image style={{ background: `url(${harry})` }} />
        </QuoteBox>

      </ContainLeft>
    );
  }
}
export default Container;
我得到的错误是:

./src/components/pages/projectpages/quotes/container.js
第64行:“getRandomName”未定义无undef

您必须在构造函数中绑定它

constructor() {
    super();
    this.state = {};
    this.getRandomName = this.getRandomName.bind(this);
  }
如果使用默认关键字导出名称数组,也可以像这样导入名称数组


将解决此问题。

您的代码是正确的。它工作得很好。如果您需要进一步帮助,请发布您收到的错误。Ravindra,我已经更新了。错误是./src/components/pages/projectpages/quotes/container.js第64行:“getRandomName”未定义没有未定义您的意思是{this.getRandomName}?{getRandomName}应该是{this.getRandomName}我想它已经接近了,但现在我得到了TypeError:无法读取未定义的属性“4”;引用此返回名称时出错。名称[Math.floorMath.random*names.length-1];从何处获取名称?从array.js,我将其导入为:import{names,sayings}from./arrays';而在arrays.js中,它的布局类似于so const names=[{name:'Yoda',id:1},];也在我上面的帖子里
constructor() {
    super();
    this.state = {};
    this.getRandomName = this.getRandomName.bind(this);
  }
import names from './arrays';