[英]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.
但不工作。
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".这不是正确的方法,因为
createText
是一个事件处理程序,它不会呈现元素,您需要的是“元素的条件呈现”。
Check Docs for more details Conditional Rendering .检查文档以获取更多详细信息Conditional Rendering 。
Steps:脚步:
1- Use a state variable with initial value false
. 1- 使用初始值为
false
的状态变量。
2- Onclick of button update the value to true
. 2-单击按钮将值更新为
true
。
3- Use that state value for conditional rendering. 3- 使用该状态值进行条件渲染。
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' />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.