// 父组件
import React, {Component} from 'react';
class Parents extends Component {
constructor(props) {
super(props);
this.state = {
}
}
componentDidMount() {
}
handleCancel = (e) => {
console.log('父组件的方法被子组件调用');
}
childClick = (e) => {
this.child.onShow()
}
render() {
return (
<section>
<Child onCancel={this.handleCancel} onRef={(ref)=>{ this.child = ref}}></Child>
<div onClick={this.childClick}>调用子组件的函数</div>
</section>
);
}
}
export default Parents;
// 子组件
import React, {Component} from 'react';
class Child extends Component {
constructor(props) {
super(props);
this.state = {
}
}
componentDidMount() {
this.props.onRef(this)
}
onShow(){
console.log('子组件的方法被父组件调用')
}
render() {
return (
<section>
<div onClick={()=>{this.props.handleCancel()}}>子组件用this.props调用父组件的函数</div>
</section>
);
}
}
export default Child;
案例中的应用
子组件定义接口规则
interface AddPersonProps {
[name: string]: any
}
若不定义使用接口规则会出现报错
同时也无法使用父组件传来的 值 与 方法
子组件中定义的方法,(需要在父组件调用的)
// 显示添加人员弹窗
public showModal = (record?) => {
this.setState({
visible: true,
id: record.id,
userName: record.user_name,
subordinateBranch: record.subordinate_branch
});
};
子组件中的生命周期
// 挂载
public componentDidMount() {
this.getOsintUser()
// 在生命周期中,将自组件最高层级this当参数传出去
this.props.onRef(this)
}
父组件定义一个索引签名
若不定义索引签名,则无法在该父组件上随意添加所需的属性
添加后也无法使用,并报错
在快速修复中,会出现提供修复的方式,可以选择添加索引签名,系统会自动完成为父组件添加索引签名的这一步
父组件中调用子组件的方法
// 编辑行
public handleEdit = (record: string | number) => {
console.log(record,'11111111');
this.child.showModal(record)
}
引入的子组件
<AddPerson list={this.getList} onRef={(ref)=> this.child = ref} />