如何在反应项目中使用状态 [英] How to use state in react project
本文介绍了如何在反应项目中使用状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 React js 的新手.我想知道如何初始化状态变量以及如何在 html 中使用状态变量.请帮助我怎么知道它.谢谢
解决方案
请参考这个例子.我编写了一个非常简单的组件,可以帮助您理解 React 中的状态.
import React, {Component, useEffect, useState} from 'react';类 MyComponent 扩展组件 {构造函数(道具){超级(道具);this.state = {names: []};}componentDidMount() {让 json = [];json.push("泰姬陵");json.push("汉密尔顿");json.push("约翰");this.setState({names: json});}使成为() {返回 (<div><div>{this.state.names.map((item, i) => {返回 {物品} })}
);}}导出默认的 MyComponent;
I am new in react js. I want to know how to initialize state variable and how I can use state variable in html. Please help me how ever knows it. Thanks
解决方案
Please follow this example. I have written a very simple component that will help you to understand state in react.
import React, {Component, useEffect, useState} from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {names: []};
}
componentDidMount() {
let json = [];
json.push("Taj");
json.push("Hamilton");
json.push("John");
this.setState({names: json});
}
render() {
return (
<div>
<div>
{this.state.names.map((item, i) => {
return <li key={i}>
{item}
</li>
})}
</div>
</div>
);
}
}
export default MyComponent;
这篇关于如何在反应项目中使用状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文