之前在 State 和生命周期 在每一个元件里面都会有自己的 state,但如果遇到彼此需要共用的 state 就会把资料放在父层,并从父层传递 props 资料跟控制 function 去修改资料给子元件。
结构示意图
之前主管分享了一个使用其他框架,元件可以互相传递资料的小练习。看到提升 State 这部分,觉得很适合用 React 改写试试。
主要是能复用元件,但点击元件会传递资料给另一个元件的动作。
以下结果:
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')
);
参考资料:
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 (交集型别)
在 App 需求中 若页面需要通过 URL 渲染远端 HTML 页面 若页面资料提供的是 html...
前天的趣味SQL, 经过大家热烈的响应,有提到 width_bucket() https://ith...
先来说说什麽是「事件」呢? 举个例子:看到红灯,就踩刹车! 「看到红灯」就是事件;「踩刹车」就是事...
叙述统计表 今天一家电脑公司为了了解该电脑在一地区销售的远景,所以利用近60天的销售报表,试求该电脑...
写在铁人赛开赛之前 不知道是否有人跟我一样,学习一门前端框架到现在,有办法写出一个称得上功能完整的网...