React Component 只能透过资料状态的改变来更新画面,而 React 元件有两种资料来源:
当 Props 或 State 改变时才会更新画面。
举个简单的例子:
在 App.js 将 name 属性传递给 Welcome.js 做使用
// App.js
import Welcome from "./Welcome";
function App() {
return (
<Welcome name="Mary"/>
);
}
export default App;
Welcome.js 接收 props
// Welcome.js
import React from 'react'
const Welcome = (props) => {
return (
<h1>Hello, {props.name}</h1>
)
}
export default Welcome
或者也可以解构赋值来接收 props,直接将要传递的属性名称放入参数里面,这样的做法就不用每次都一直写 props 了,也可以比较清楚知道是什麽资料被传进去
// Welcome.js
import React from 'react'
const Welcome = ({ name }) => {
return (
<h1>Hello, { name }</h1>
)
}
export default Welcome
若使用 class component,则要将 render() 内的 props 替换成 this.props:
// Welcome.js
import React, { Component } from 'react';
class Welcome extends Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
export default Welcome
无论是使用 function component 或是 class component 最终结果都相同,网页上都会显示 Hello, Mary
例如:
import React, { Component } from "react";
class ClassState extends Component {
constructor() {
// super 呼叫 component 的 constructor
super();
// count 的初始值设为 0
this.state = { count: 0 };
}
render() {
return (
<div>
<h3>Class component - state</h3>
<p>You clicked {this.state.count} times</p>
<button
onClick={() => {
// 利用 setState 改变状态,使 component 重新 render
this.setState({ count: this.state.count + 1 });
}}
>
Click
</button>
</div>
);
}
}
export default ClassState;
上面的例子因为 constructor() 内 count 初始值设为 0,打开网页会看到画面如下:
利用 this.setState() 改变状态时,点击按钮时画面就会更新,点击几次画面就会被更新几次,下图为点击按钮 10 次後的画面,被点击的次数变成 10。
参考资料:
https://www.fooish.com/reactjs/state.html
故事依时间序简述 故事背景:某航空公司(以下简称某航) 某航於2017上半年裁员,共计裁减约600名...
前言 就小女子浅见,现在iOS开发有几个选项: React Native Flutter Swift...
Gradient Descent Method 统整一下到底要如何Gradient Descent...
本篇大纲:Enter / Update / Exit 状态、增减资料数量与DOM元素不匹配的方法、...
3D场景的基础 基础的要素:物体、光源、材质与摄影机 基础几何形状 平面 plane() 长方体 b...