单击按钮时如何渲染元素:ReactJS [英] How to render element on click of button: ReactJS

查看:175
本文介绍了单击按钮时如何渲染元素:ReactJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在您单击按钮后立即呈现一个段落。

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

这是我的代码。

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.

推荐答案

这不是正确的方法,因为 createText 是一个事件处理程序,它不会呈现元素,你需要的是条件呈现元素。

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.

步骤:

1-使用状态变量,初始值 false

1- Use a state variable with initial value false.

2-点击按钮将值更新为 true

2- Onclick of button update the value to true.

3-使用状态值进行条件渲染。

3- Use that state value for conditional rendering.

工作代码:

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' />

这篇关于单击按钮时如何渲染元素:ReactJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆