新建 forum.jsx 父組件。
import React from 'react'; import ForumDetail from './forumDetail'; export default class Forum extends React.Component { constructor(props) { super(props); this.state = { type: 1 }; } render() { return ( <div> <ForumDetail value={this.state.type} /> </div> ) } }
新建 forumDetail.jsx 子組件。
import React from 'react'; export default class Forum extends React.Component { constructor(props) { super(props); this.state = { type: '' }; } render() { return ( <div> {`父組件傳過來的值${this.state.type}`} </div> ) } // 獲取父組件傳過來的值,這里還可以監聽父組件傳值變了,然后重新賦值給 state。 // props 表示父組件傳過來的值, state 表示當前子組件的state。 static getDerivedStateFromProps(props,state) { // 父組件傳過來的 type 和 子組件的 type 不一樣,那么子組件重新賦值。 // 也可以理解成,父組件傳過來的值變了。 if (props.type !== state.type) { // 這里執行相應的方法 // console.log(123); return { type,//把父組件最新的props.type重新賦值到 子組件state.type } } // 父組件的值沒有變化,這里不做任何操作。 return null } }