日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

深入理解React?三大核心屬性_React

作者:s_kzn ? 更新時間: 2022-04-25 編程語言

1、State 屬性

React 把組件看成是一個狀態機(State Machines)。通過與用戶的交互,實現不同狀態,然后渲染 UI,讓用戶界面和數據保持一致。

React 里,只需更新組件的 state,然后根據新的 state 重新渲染用戶界面(不要操作 DOM)。

import React from 'react ';
import ReactDom from 'react-dom';
?
?
class Student extends React.Component{
? ? constructor() {
? ? ? ? super();
? ? ? ? this.state={
? ? ? ? ? ? name:'花少北'
? ? ? ? }
? ? }
? ? render() {
? ? ? ? this.state.name='老番茄';
? ? ? ? return 

{this.state.name}

? ? } } ReactDOM.render(,document.getElementById('root'))

在React中,一個組件中要讀取當前狀態需要訪問 this.state, 而 state 是可以被修改的,但是,要更新數據直接給 this.state 賦值是不可行的,必須要使用 setState()

?this.setState() {
? ? ? ? name:'某幻'
? ? }

(1)setState 不會立刻改變React組件中state的值.

(2)setState 通過觸發一次組件的更新來引發重繪.

(3)多次 setState 函數調用產生的效果會合并。

2、Props ?屬性

react中說的單向數據流值說的就是props,根據這一特點它還有一個作用:組件之間的通信。props本身是不可變的,但是有一種情形它貌似可變,即是將父組件的state作為子組件的props,當父組件的state改變,子組件的props也跟著改變,其實它仍舊遵循了這一定律:props是不可更改的。

props屬性的特點

1.每個組件對象都會有props(properties的簡寫)屬性

2.組件標簽的所有屬性都保存在props中

3.內部讀取某個屬性值:this.props.propertyName

4.作用:通過標簽屬性從組件外 向組件內傳遞數據(只讀 read only)

5.對props中的屬性值進行類型限制和必要性限制

類組件:

import React from 'react ';
import ReactDom from 'react-dom';
// 函數組件
function ?Student(props){
? ? return 

{props.name} {props.address}

} ? const ?Stu={ ? ? name:'某幻', ? ? ? ? address:'青島' } ? ReactDOM.render(,document.getElementById('root'))

?函數組件:

import React from 'react ';
import ReactDom from 'react-dom';
class Student extends React.Component{
? ? render() {
? ? ?return(
? ? ? ? ?

{this.props.name} {this.props.address}

? ? ?) ? ? } } const ?Stu={ ? ? name:'某幻', ? ? ? ? address:'青島' } ReactDOM.render(,document.getElementById('root'))

props 屬性 和 state 屬性的區別

  • props中的數據都是外界傳遞過來的;
  • state中的數據都是組件私有的;(通過Ajax獲取回來的數據,一般都是私有數據)
  • props中的數據都是只讀的,不能重新賦值;
  • state中的數據,都是可讀可寫的;
  • 子組件只能通過props傳遞數據;

3、Refs ?屬性?

定義:組件內的標簽可以定義ref屬性類標識自己,有點類似與JS中的id

React文檔中再三強調,請不要過度使用refs,所以當我們可以用dom原生對象解決時,盡量不要使用refs 依照之前的寫法,首先是給出類組件和函數組件中refs的寫法

ref 的三種形式

(1)字符串形式

【官方不推薦】

class App extends React.Component{
? ? changeInput = ()=>{
? ? ? ? const {input} = this.refs
? ? }
? ? render() {
? ? ? ? return (
? ? ? ? ? ? 
? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ) ? ? } }

(2)函數回調形式

class App extends React.Component{
? ? changeInput = ()=>{
? ? ? ? console.log(this.inputRef);
? ? }
? ? render() {
? ? ? ? return (
? ? ? ? ? ? 
? ? ? ? ? ? ? ? {this.inputRef = el}}/> ? ? ? ? ? ?
? ? ? ? ) ? ? } }

(3)createRef 創建 ref 容器

【目前官方最推薦的一種】

class App extends React.Component{
? ? inputRef = React.createRef()
? ? changeInput = ()=>{
? ? ? ? console.log(this.inputRef.current);
? ? }
? ? render() {
? ? ? ? return (
? ? ? ? ? ? 
? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ) ? ? } }

函數組件的寫法

function App(){
? ? const inputRef = useRef("")
? ? return (
? ? ? ? 
? ? ? ? ? ? ? ? ? ?
? ? ) }

原文鏈接:https://blog.csdn.net/m0_61700036/article/details/123036025

欄目分類
最近更新