在React中的onClick事件之后渲染多个元素

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (275)

我在尝试在onClick事件发生后在反应组件中渲染两个反应元素时遇到问题。想知道这是否可能?我确定我搞乱了三元运算符,但是我想不出另一种方法去做我想做的事情?

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
          }

另一种“和”,用于切换showElementstate刚够 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;

扫码关注云+社区

领取腾讯云代金券

玩转腾讯云 有奖征文活动