最新答案(React-hooks獲取函數(shù)式子組件內(nèi)容):
// 子組件
import React, {useImperativeHandle} from 'react';
const FunctionComponent = React.forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
click: handleClick,
ref: ref.current,
}));
const handleClick =() => {
console.log('hulala')
};
return (
<div onClick={handleClick} ref={ref} style={{width: '100px'}}>
hulala
</div>
);
});
export default FunctionComponent;
// 父組件
const App = () => {
const Dd = useRef();
useEffect(() => {
console.log(Dd, 'Dd');
}, []);
return (
<FunctionComponent ref={Dd}/>
)
};
以下為很久以前的原答案,雖然好理解,但是不方便也不利于代碼維護(hù),不推薦下面的方法,還是用Ref吧.
先上代碼:
<OperateStudentForm
onGetFunc={func => {
this.handleOpenModal = func;
}}
onSearch={this.handleSearch}
/>
</Card>
);
}
}
export default StudentManagement;
componentDidMount() {
this.props.onGetFunc(this.handleOpenModal);
}
handleOpenModal = data => {
this.setState({
visible: true,
data,
});
};
- 在子組件初始化的時(shí)候,將方法名傳遞給父父組件,父組件通過接受子組件傳遞過來的func,綁定到父組件的this上,這樣就能隨意調(diào)用子組件的方法了.
- 注意,調(diào)用this.handleOpenModal盡量不要寫在元素內(nèi)聯(lián)里面,最好用一個(gè)方法包一層,不然可能會(huì)出現(xiàn)調(diào)用不到這個(gè)函數(shù)的情況.
- 不太喜歡網(wǎng)上的各種ref的方式調(diào)用,會(huì)使代碼結(jié)構(gòu)混亂,而且非常不React.
- react-hooks時(shí)代應(yīng)該不是這樣玩的,應(yīng)該會(huì)更優(yōu)雅,還還沒怎么研究
I believe your apartment is on fire