父组件向子组件传值-----props
父组件:
import React, { Component } from 'react';
import Child from './Child';
class Parent extends Component {
state = {
parentStatus: 'parent'
}
showParent = () => {
console.log('I am parentComponent.')
}
render() {
const { parentStatus } = this.state;
return (
<>
<div>
这里是父组件!
</div>
<Child
parentStatus={parentStatus}
showParent={this.showParent}
/>
</>
);
}
}
export default Parent;
子组件:
import React, { Component } from 'react';
class Child extends Component {
state = {
childStatus: 'child'
}
componentDidMount = () => {
const { showParent } = this.props;
//调用父组件的方法
showParent() // 输出:I am parentComponent.
console.log(this.state.parentStatus) // 输出:parent
}
showChild = () => {
console.log('I am childComponent.')
}
render() {
return (
<div>
这里是子组件!
</div>
);
}
}
export default Child;
总结:将父组件的方法或者状态在子组件入口传进去,在子组件里可直接在this.props中获取使用。
子组件向父组件传值
父组件:
import React, { Component } from 'react';
import Child from './Child';
class Parent extends Component {
state = {
parentStatus: 'parent'
}
showParent = () => {
console.log('I am parentComponent.')
}
handleClick = () => {
const { showChild } = this.child;
const { childStatus } = this.child.state;
//调用子组件的方法
showChild() // 输出:I am childComponent.
console.log(childStatus) // 输出:child
}
render() {
return (
<>
<div onClick={this.handleClick}>
这里是父组件!
</div>
<Child
onRef={r => (this.child = r)}
/>
</>
);
}
}
export default Parent;
子组件:
import React, { Component } from 'react';
class Child extends Component {
state = {
childStatus: 'child'
}
componentDidMount = () => {
const { onRef } = this.props;
onRef(this) //将子组件的this回传
}
showChild = () => {
console.log('I am childComponent.')
}
render() {
return (
<div>
这里是子组件!
</div>
);
}
}
export default Child;
子组件的onRef(this)将this回传,父组件中this.child既是子组件的this,因此在父组件中this.child即可直接使用子组件的方法或状态。