在react中,如何实现类组件的显示
我们可以在render函数中返回数据,如下所示:
render(){
// 1.react元素:通过JSX编写的代码就会被编译成React.createElement,
// 所以返回的就是一个React元素
// 2.组件或者fragments
return ["abc","cba","nba"]
}这样我们就可以得到一个abccbanba的字符串了,原理是什么呢?这就是render函数的作用,就比如假如我们在constructor函数中定义一个状态message在render函数中打印是什么结果呢?如下图代码所示
import React from "react";
/* 1.类组件 */
class App extends React.Component {
constructor(){
super()
this.state = {
message:"App Component"
}
}
render(){
const { message } = this.state
console.log(message);
return true
}
}
export default App;那么我们会在控制台打印出什么内容?对,他就是App Component,这就是React的魅力,JSX语法的强大之处。
假如我们希望返回一个标题,一个段落带HTML元素标签的内容呢?请看下面代码:
import React from "react";
/* 1.类组件 */
class App extends React.Component {
constructor(){
super()
this.state = {
message:"App Component"
}
}
render(){
// 组件或者fragments
return [
<h1>h1元素</h1>,
<h2>h2元素</h2>,
<div>哈哈哈</div>
]
}
}
export default App;这样我们就会得到一个带元素的html网页,然后细心的你会发现控制台有一句报错语句 App_class.jsx:33 Warning: Each child in a list should have a unique "key" prop. See......,这里我想说没关系,这里提示的是说没有绑定唯一值key,和我们vue中的key差不多。后面我们会讲到如何解决这个报错,尽请关注。
如何输出hello world
对了,最后我们来输出第一个程序输出,比如最经典的Hello World程序,如下代码就行了
import React from "react";
/* 1.类组件 */
class App extends React.Component {
constructor(){
super()
this.state = {
message:"App Component"
}
}
render(){
// 字符串/数字类型
return "Hello World"
}
}
export default App;好了,今天就先到这里,以后再发新内容。谢谢观看
It's not my first time to pay a visit this web page, i am visiting this website dailly and get good facts from here every day.
Hello, i think that i saw you visited my site so i got here to go back the want?.I'm trying to find things to improve my web site!I suppose its adequate to use a few of your concepts!!
Touche. Outstanding arguments. Keep up the great effort.
Wow, this post is good, my younger sister is analyzing these things, therefore I am going to let know her.
There's certainly a lot to learn about this topic. I like all the points you've made.
所有文章都令人印象深刻。由衷感谢 带来的灵感。
你 百分百 分享经验。坚持!
不常看到, 这么高质量的内容。谢谢。
@十二使徒岩 哪张图片?
照片令人惊艳。继续保持 心情。