[英]Passing ref to class component from functional component
我的 react-native 應用程序中有一個父功能組件,還有一個子 class 組件。 我想在我的父組件中調用一個子方法。 我嘗試將 ref 傳遞給 child 並使用它在 parent 中調用我的方法。
我的父組件:
const Screen = ({...props}) => {
// ...
let cats;
const onHeadSearchPress = () => {
console.log('check', cats); // log undefined
cats.toggleCategoryList();
cats.renderSearch();
};
retrun (
// ...
<Categories onRef={ref => (cats = ref)} />
// ...
)
}
我的子組件:
class Component extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
//..
};
toggleCategoryList() {
if (this.state.showList === false) {
Animated.timing(this.animateChevronY, {
toValue: 1,
duration: 300,
useNativeDriver: true,
easing: Easing.linear,
}).start();
}
if (this.state.showList === true) {
Animated.timing(this.animateChevronY, {
toValue: 0,
duration: 300,
useNativeDriver: true,
easing: Easing.linear,
}).start();
}
setTimeout(() => {
this.setState({
showList: !this.state.showList,
});
}, 100);
}
renderSearch() {
this.setState({
showSearch: true,
});
Animated.timing(this.searchBoxFade, {
toValue: 1,
duration: 200,
easing: Easing.linear,
}).start();
}
componentDidMount() {
console.log('checkthis', this); // log correctly
this.props.onRef(this);
}
render() {
// ...
}
}
但是登錄父項使未定義並且方法未運行並出現錯誤“無法讀取未定義的屬性(正在讀取toggleCategoryList)”
如果我理解,您不需要 onRef 事件。 您可以使用參考。 如果你的應用程序在第一次渲染時崩潰,應該有一個 null 檢查。
if(cats){
cats.toggleCategoryList?.();
cats.renderSearch?.();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.