React父子通信,即父组件将一个函数作为子组件的props传给子组件,子组件在恰当时候调用
如果是爷孙通信,则爷爷组件要先传给父组件,父组件再传给子组件,以此类推
**
示例1:龟兔赛跑
http://js.jirengu.com/dupajiduvi/4/edit?html,js,output
将函数组件改为class组件,通过inline style让兔子动起来
class Track1 extends React.Component {
constructor(){
super()
let n = 0
this.state = {
style: {
transform: `translate(${n}%)` // 这里是对象,属性值要加引号
}
}
let intervalID = setInterval(()=>{
n += 10
this.setState({
style: {
transform: `translate(${n}%)`
}
})
if (n >= 100) {
clearInterval(intervalID)
}
},1000)
}
render(){
return (
<div>
<div style={this.state.style}>🐇</div>
<div className='track'></div>
</div>
)
}
}
给组件传一个回调函数,当兔子跑完时,显示信息
function App(){
let success = (x)=>{
console.log(`我是${x},我到终点了`)
}
return (
<div>
<div className="header">
<Time1 />
<Referee />
<Time2 />
</div>
<Track1 success={success}/>
<Track2 success={success}/>
</div>
)
}
class Track1 extends React.Component {
// ...
if (n >= 100) {
clearInterval(intervalID)
this.props.success('兔子') // 调用
}
},1000)
}
// ...
}
要记录时间,并传给Timer组件,用函数组件行不通,改用class
class App extends React.Component {
constructor(){
super()
this.state = {
result1: 0,
result2: 0,
}
this.t0 = new Date()
}
success(x) {
console.log(`我是${x},我到终点了`)
if(x==='兔子'){
this.setState({
result1: new Date() - this.t0
})
} else if (x === '乌龟'){
this.setState({
result2: new Date() - this.t0
})
}
}
render(){
return (
<div>
<div className="header">
<Time1 time={this.state.result1}/>
<Time2 time={this.state.result2}/>
</div>
<Track1 success={this.success.bind(this)}/>
<Track2 success={this.success.bind(this)}/>
</div>
)
}
}
function Time1(props){
return (
<div>
<h3>🐇用时</h3>
<div>{props.time}</div>
</div>
)
}
在Track1和Track2组件外再加一层,变成爷孙组件
class App extends React.Component {
// ...
render(){
return (
<div>
<div className="header">
<Time1 time={this.state.result1}/>
<Time2 time={this.state.result2}/>
</div>
<Playground success={this.success.bind(this)}/>
</div>
)
}
}
function Playground(props){
return (
<div>
<Track1 success={props.success}/>
<Track2 success={props.success}/>
</div>
)
}
// ...
示例2:子组件修改父组件数据
调用父组件的函数进行修改
http://js.jirengu.com/ximocaqeki/1/edit?html,js,output
class App extends React.Component {
constructor(){
super()
this.state = {
message: "hello"
}
}
changeMsg(x) {
this.setState({
message: x
})
}
render(){
return (
<div>
<Child message={this.state.message} fn={this.changeMsg.bind(this)}/>
</div>
)
}
}
function Child(props){
return (
<div>
<p>我得到的信息是 {props.message}</p>
<button onClick={()=>props.fn('ahahahahaha')}>click</button>
</div>
)
}
ReactDOM.render(<App />, document.querySelector("#root"))