Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
496 views
in Technique[技术] by (71.8m points)

javascript - How to render element on click of button: ReactJS

I am trying to render a paragraph as soon as the you click the button.

Here is my code.

import React, { Component } from 'react';

class App extends Component {
  constructor() {
    super();
    this.createText = this.createText.bind(this);
  }


  createText() {
    return(
      <p>hello friend</p>
    )
  }


  render() {
    return (
      <div className="App">
        <button onClick={this.createText}>Click</button>
      </div>
    );
  }
}

export default App;

Here I am trying to render "hello friend" when the button is clicked. But is not working.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is not the correct way because createText is a event handler it will not render the element, what you need is "Conditional rendering of elements".

Check Docs for more details Conditional Rendering.

Steps:

1- Use a state variable with initial value false.

2- Onclick of button update the value to true.

3- Use that state value for conditional rendering.

Working Code:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      isShow: false
    }
    this.createText = this.createText.bind(this);
  }


  createText() {
    this.setState({ isShow: true }) 
  }


  render() {
    return (
      <div className="App">
        <button onClick={this.createText}>Click</button>
        {this.state.isShow && <p>Hello World!!!</p>}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id='app' />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...