React从状态中的多个数组传递道具

时间:2017-08-06 12:49:40

标签: javascript reactjs ecmascript-6

我正在尝试从两个包含在react组件状态中的数组中传递props。一个数组由用户生成,另一个数组已经内置。这有点过头了,因为我还是React的新手并且不确定如何正确传递道具。

组件中没有错误,只是我不知道该怎么做。

我将在下面解释我正在寻找什么,任何帮助将不胜感激

主要组件

this.state下方,您会看到questions(效果很好),然后hints。问题是正确映射的,但是当我尝试添加提示以与其一起映射时,它会立即返回所有提示而不是按顺序逐个返回。我试过添加(questions, hints),但它没有正确返回。

export default class AutoFocusText extends Component {
  constructor() {
    super();

    this.state = {
      active: 0,
      questions: [
        '1. Enter A Proper Noun',
        '2. Enter A Location',
        '3. Enter A Proper Noun that Describes Evil',
        '4. Describe Something Menacing',
        '5. Describe a fortified area',
        "6. A Woman's Name",
        '7. Describe a large area of mass'
      ],
      hints: [
        "Hint: Use words like Rebel, Hell's Angels",
        'Hint: Use a word such as Base, Bunker, Foxhole, Bedroom',
        'Hint: Use words like Empire, Ottoman, Mongols',
        'Hint: Freeze Ray, Leftover Fruitcake',
        'Hint: Castle, Bunker, Planet',
        'Hint: Astrid, Diana, Mononoke, Peach',
        'Hint: Use words such as Galaxy, Planet, Wal Mart'
      ],
      answers: []
    };

我想收集用户对答案的输入并将其作为道具传递到另一个组件,例如properName1={this.state.value1}等等,我知道这是映射一系列答案,我只是不确定如何这样做。

以下是主要组件的其余部分。

    this.submitHandler = this.submitHandler.bind(this);
    this.renderQuestion = this.renderQuestion.bind(this);
    this.onChange = this.onChange.bind(this);
  }

  renderQuestion() {
    const { questions, hints, active, value } = this.state;

    if (active >= questions.length)
      return <Crawler style={{ width: '500px', position: 'absolute' }} />;

    return questions.filter((quest, index) => index === active).map(quest => ( // get next question // map over selected question, the key prop allows react to
      <FormElement
        key={active}
        text={quest}
        hint={hints}
        value={value}
        onChange={this.onChange}
      />
    ));
  }

  onChange(e) {
    this.setState({ value: e.target.value });
  }

  submitHandler(e) {
    e.preventDefault();

    const answers = [...this.state.answers, this.state.value]; //push new value to answsers array without mutation
    const value = ''; // clear input
    const active = this.state.active + 1; // index pointer

    this.setState({ answers, value, active });
  }

  render() {
    return (
      <MainContainer>

        <DivStyle>
          {/* Form Wrapper */}
          <form onSubmit={this.submitHandler}>
            {this.renderQuestion()}
            <SubmitButton type="submit">Submit</SubmitButton>
          </form>
          <ul>
            {this.state.answers.map((ans, index) => {
              return (
                <li key={index}>
                  {ans}
                </li>
              );
            })}
          </ul>
        </DivStyle>
      </MainContainer>
    );
  }
}

子组件1 这是一个愚蠢的组件,其中问题(以及我想要提示的位置)生成

class FormElement extends Component {
  constructor() {
    super();
  }

  componentDidMount() {
    //focus text input upon mounting component
    this.textInput.focus();
  }

  render() {
    const { text, hint, value, onChange } = this.props;

    return (
      <div>
        <InputQuestion>
          {text}
          {hint}
        </InputQuestion>
        <input
          className="inputstyling"
          ref={el => {
            this.textInput = el;
          }}
          onChange={onChange}
          type="text"
          value={value}
        />
      </div>
    );
  }
}

export default FormElement;

目前,“提示”会立即引入所有提示,而不是一次提供一个提示。

子组件2

最后需要通过的道具才能到达这里。数组正在抛弃我,因为我从未通过数组传递道具

class Crawler extends Component {
  constructor() {
    super();
    this.state = {
      properName1: 'Rebel',
      noun1: 'frog',
      properName2: 'Empire',
      properName3: 'DEATH STAR',
      noun2: 'station',
      noun3: 'planet',
      personsName1: 'Leia',
      noun4: 'starship',
      pluralnoun1: 'people',
      noun5: 'galaxy'
    };
  }
  render() {
    return (
      <ContainLeft style={{ padding: 0 }}>

        <CrawlHolder>
          <div class="fade" />
          <section className="star-wars">

            <div className="crawl">

              <div className="title">
                <p>Episode IV</p>
                <h1>A New Hope</h1>
              </div>

              <p>
                It is a period of civil war.
                {' '}
                {this.props.properName1}
                {' '}
                spaceships, striking from a hidden
                {' '}
                {this.props.noun1}
                , have won their first victory against the evil Galactic
                {' '}
                {this.props.properName2}
                .
              </p>
              <p>
                During the battle,
                {' '}
                {this.props.properName1}
                {' '}
                spies managed to steal secret plans to the
                {' '}
                {this.props.properName2}
                's ultimate weapon, the
                {' '}
                {this.props.properName3}
                , an armored
                {' '}
                {this.props.noun2}
                {' '}
                with enough power to destroy an entire planet.
              </p>
              <p>
                Pursued by the Empire’s sinister agents, Princess
                {' '}
                {this.props.personsName1}
                {' '}
                races home aboard her starship, custodian of the stolen plans that can save her people and restore freedom to the
                {' '}
                {this.props.noun3}
                …
              </p>

            </div>

          </section>
        </CrawlHolder>
      </ContainLeft>
    );
  }
}
export default Crawler;

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

map中的函数有一个可选的第二个参数,当前元素的索引可以这样做:

return questions.filter((quest, index) => index === active).map((quest,i) => (
      <FormElement
        key={active}
        text={quest}
        hint={hints[i]}
        value={value}
        onChange={this.onChange}
      />
    ));

编辑:

我现在看到你一次只渲染一个问题所以我认为不需要map;因为你有当前问题的索引(active),我认为你可以

return (
    <FormElement
        text={questions[active]}
        hint={hints[active]}
        value={value}
        onChange={this.onChange}
    />
)