事件傳遞: 父傳子、子傳父;
父傳子
簡單實(shí)例:
// 父組件
import React, { Component } from 'react';
import Button from './button'
class App extends Component {
render () {
return (
<Button sizeCount={ 0 }/Button>
)
}
}
// button.js
class App extends Component {
constructor(props) {
this.state = { count: this.props.sizeCount}
this.sizeCountAdd = this.sizeCountAdd.bind(this)
}
this.sizeCountAdd () {
this.setState({count: this.state.count + 1})
}
render () {
return (
<button onClick={this.sizeCountAdd}>點(diǎn)擊增加</button>
)
}
}
子傳父
簡單實(shí)例:
// 父組件
class App extends React.Component {
constructor(props) {
super(props);
this.status = this.status.bind(this)
this.state = {
status: 'true'
};
}
status (sta) {
this.setState({status: sta.toString()})
}
render() {
console.log('enter ControlPanel render')
return (
<div className="App" >
<Home onUpdate = {this.status} />
<span>{this.state.status}</span>
</div>
)
}
}
// Home.js 子組件
class Home extends React.Component {
constructor(props) {
super(props)
this.state = {
status: true,
count: 0
}
this.add = this.add.bind(this)
}
componentWillMount() {
console.log('我在render前執(zhí)行了'+this.state.count)
}
add () {
this.setState(state => ({
status: !state.status,
count: state.status === true ? '1' : '0'
}))
this.props.onUpdate(this.state.status)
}
render() {
return (
<div>
<button onClick={this.add}>{this.state.count}</button>
</div>
)
}
}
同級(jí)組件傳值
簡單實(shí)例:
方法一: 通過父組件作為媒介;
通過 子傳父抖剿,然后父傳子進(jìn)行實(shí)現(xiàn);
方法二:
// 暫定