提升 State ( Day12 )

之前在 State 和生命周期 在每一个元件里面都会有自己的 state,但如果遇到彼此需要共用的 state 就会把资料放在父层,并从父层传递 props 资料跟控制 function 去修改资料给子元件。

结构示意图

提升 State 小练习

之前主管分享了一个使用其他框架,元件可以互相传递资料的小练习。看到提升 State 这部分,觉得很适合用 React 改写试试。
主要是能复用元件,但点击元件会传递资料给另一个元件的动作。

  1. 在父层元件写入共用资料
  2. 使用 props 将「function」传递进去进行修改父元件的资料

以下结果:

class Calling extends React.Component {
  constructor(props) {
    super(props);
    this.handleCalling = this.handleCalling.bind(this);
  }

  handleCalling(e) {
    const callingTo = this.props.role  === 'brother' ? 'sister' : 'brother'
    this.props.calling(callingTo)
  }

  render() {
    return (
      <div className="comp">
        <p>Hello, I'm { this.props.role }.</p>
        <button onClick={this.handleCalling} >
            Message To { ( this.props.role === 'brother') ? 'Sister' : 'Brother' }
        </button>
            {  this.props.isMomCalling ? <p className="mom">Mom said do your homework!</p> : '' }
      </div>
    );
  }
}

class Room extends React.Component {
  constructor(){
    super();
    this.state = {
      sister: {
        isMomCalling: false
      },
      brother: {
        isMomCalling: false
      }
    }
    this.calling = this.calling.bind(this)
  }
  
  calling = (who) => {
   this.setState({
     [who]: {
       isMomCalling: true
     }
   })
  }
  
  render() {
    return (
      <div id="app">
        <Calling isMomCalling={this.state.brother.isMomCalling} calling={this.calling} role="brother" />
        <Calling isMomCalling={this.state.sister.isMomCalling} calling={this.calling} role="sister" />
      </div>
    );
  }
}

ReactDOM.render(
  <Room />,
  document.getElementById('root')
);

Codepen 连结

参考资料:
https://zh-hant.reactjs.org/docs/lifting-state-up.html
https://stackblitz.com/edit/vue-uzoild?file=src/App.vue


<<:  [机派X] Day 14 - 下一站,幸福。终於结束累人的安装苦工了

>>:  Day11:【TypeScript 学起来】只有 TS 才有的型别 : Union Types(联合型别) / Intersection types (交集型别)

[ 卡卡 DAY 19 ] - React Native 用 react-native-webview 实现 webview 跟 html render

在 App 需求中 若页面需要通过 URL 渲染远端 HTML 页面 若页面资料提供的是 html...

以Postgresql为主,再聊聊资料库 width_bucket() 的介绍

前天的趣味SQL, 经过大家热烈的响应,有提到 width_bucket() https://ith...

【Day24】派一个Spy到网页中窃听—事件监听

先来说说什麽是「事件」呢? 举个例子:看到红灯,就踩刹车! 「看到红灯」就是事件;「踩刹车」就是事...

DAY9-EXCEL统计分析:常用的统计量

叙述统计表 今天一家电脑公司为了了解该电脑在一地区销售的远景,所以利用近60天的销售报表,试求该电脑...

[铁人赛 Day01] 文章架构、预计内容,以及适用范围

写在铁人赛开赛之前 不知道是否有人跟我一样,学习一门前端框架到现在,有办法写出一个称得上功能完整的网...