建立Context.js
import React from 'react'; const DocsContext = React.createContext(); export default DocsContext;
父组件:
import DocsContext from './docsContext';
import Children from './chlidren';
class Person extends Component {this.docsRef = React.createRef(null);
constructor(props) {
super(props);
this.state = { id:3 }
}this.docsRef.current && this.docsRef.current.getList();
//父组件获取子组件传过来的值,做处理 getDetail = item => {
console.log(item)
//父组件调用子组件的方法
} <DocsContext.Provider value={{ getDetail:val => this.getDetail(val)}} > <Children id={this.state.id} childRef={this.docsRef} />
</DocsContext.Provider> }
子组件:
import React, {useContext,useImperativeHandle} from 'react';
import DocsContext from './docsContext'; const Children: React.FC = ({id, childRef}) => { const values = useContext(DocsContext); //子组件调用父组件方法 const handle = (item)=>{ values.getDetail(item); }useImperativeHandle(childRef, () => ({ getList: () => { queryFileList(); }, }));
const queryFileList = ()=>{}
}
标签:DocsContext,const,--,React,item,组件,import From: https://www.cnblogs.com/Super-scarlett/p/16983224.html