事件传递: 父传子、子传父;
父传子
简单实例:
// 父组件
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}>点击增加</button>
)
}
}
子传父
简单实例:
// 父组件
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前执行了'+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>
)
}
}
同级组件传值
简单实例:
方法一: 通过父组件作为媒介;
通过 子传父,然后父传子进行实现;
方法二:
// 暂定