簡體   English   中英

在React中的onClick事件之后呈現多個元素

[英]rendering multiple elements after onClick event in React

我遇到一個問題,試圖在onClick事件之后在react組件內呈現兩個react元素。 想知道這是否有可能? 我確定我搞砸了三元運算符,但是我無法想到另一種方法來做我想做的事情?

TL; DR :“單擊按鈕時,我看到elementA elementB”

這是代碼片段:

import React, { Component } from 'react';

class MyComponent extends Component {
    constructor(props) {
    super(props)
    this.state = { showElement: true };
    this.onHandleClick = this.onHandleClick.bind(this);
  }

  onHandleClick() {
    console.log(`current state: ${this.state.showElement} and prevState: ${this.prevState}`);
    this.setState(prevState => ({ showElement: !this.state.showElement }) );
  };


  elementA() {
    <div>
      <h1>
      some data
      </h1>
    </div>
  }


  elementB() {
    <div>
      <h1>
      some data
      </h1>
    </div>
  }

  render() {
    return (
      <section>
          <button onClick={ this.onHandleClick } showElement={this.state.showElement === true}>
          </button>
          { this.state.showElement
            ?
            null
            :
            this.elementA() && this.elementB()
          }
      </section>
    )
  } 
}

export default MyComponent;

你只是不專心。

elementA() {
    return ( // You forget
        <div>
            <h1>
                some data
            </h1>
        </div>
    )
}

與元素B相同。

如果您想同時查看這兩個組件,則應將三元組更改為

{ this.state.showElement
            ?
            <div> {this.elementA()} {this.elementB()}</div>
            :
            null
          }

另一個“和”,用於在state切換showElement就足夠了this.setState({showElement: !this.state.showElement });

請嘗試以下操作(我將在代碼中添加注釋,以解釋發生了什么事情):

function SomeComponentName() { // use props if you want to pass some data to this component. Meaning that if you can keep it stateless do so.
  return (
    <div>
      <h1>
      some data
      </h1>
    </div>
  );
}

class MyComponent extends Component {
  constructor(props) {
    super(props)
    this.state = { showElement: false }; // you say that initially you don't want to show it, right? So let's set it to false :)
    this.onHandleClick = this.onHandleClick.bind(this);
  }

  onHandleClick() {
    this.setState(prevState => ({ showElement: !prevState.showElement }) ); 
    // As I pointed out in the comment: when using the "reducer" version of `setState` you should use the parameter that's provided to you with the previous state, try never using the word `this` inside a "reducer" `setState` function
  };

  render() {
    return (
      <section>
          <button onClick={ this.onHandleClick } showElement={this.state.showElement === false}>
          </button>
          { this.state.showElement
            ? [<SomeComponentName key="firstOne" />, <SomeComponentName key="secondOne" />]
            : null
          }
      </section>
    )
  } 
}

export default MyComponent;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM